#!/usr/bin/env python
# -*- coding:UTF-8 -*-
from django.http import HttpResponse, HttpResponseRedirect, StreamingHttpResponse, JsonResponse
from django.shortcuts import render, render_to_response
from django.template import RequestContext
from django import forms

import sys
import traceback
import logging
import cgi, cgitb
from os import environ
from string import strip, split
import datetime, time
from time import strftime, gmtime
import MySQLdb
import base64
import socket
from struct import *
import ctypes
import json
import hashlib
import os
import csv
import codecs
import web_XZDQ_V1_0.MySQLDB as MySQLDB
import web_XZDQ_V1_0.PowerID as PowerID
import web_XZDQ_V1_0.Common as Common
import web_XZDQ_V1_0.FileUtil as FileUtil
from django.views.decorators.csrf import csrf_exempt


# Create your views here.

# 装饰器html 权限验证 系统管理id=18
def auth(func):
    def inner(request):
        # 权限验证
        menudate = []
        try:
            userid = request.COOKIES['userid']
            row0 = MySQLDB.SelectMySql("SELECT role_id FROM t_sys_user WHERE user_id = %s AND status = 1;" % userid)
            # if row0[0][1] == 0:
            #    response = render(request,'login.html', {})
            #    return response
            row1 = MySQLDB.SelectMySql("SELECT menu_id FROM t_role_menu WHERE role_id = %s;" % row0[0][0])
            for i in range(len(row1)):
                menudate.append(row1[i][0])
        except:
            pass
        if 18 not in menudate:
            # return HttpResponseRedirect('/')
            response = render(request, 'login.html', {})
            return response
        # 多用户登录验证
        md5str = request.COOKIES['loginmd5']
        row0 = MySQLDB.SelectMySql("SELECT user_id FROM t_sys_user WHERE valid_md5 = '%s';" % md5str)
        try:
            if str(row0[0][0]) == userid:
                pass
            else:
                # return HttpResponseRedirect('/')
                response = render(request, 'login.html', {})
                return response
        except:
            # return HttpResponseRedirect('/')
            response = render(request, 'login.html', {})
            return response
        return func(request)

    return inner


# 装饰器json 权限验证 系统管理id=18
def authjson(func):
    def jnner(request):
        # 权限验证
        menudate = []
        try:
            userid = request.COOKIES['userid']
            row0 = MySQLDB.SelectMySql("SELECT role_id FROM t_sys_user WHERE user_id = %s AND status = 1;" % userid)
            row1 = MySQLDB.SelectMySql("SELECT menu_id FROM t_role_menu WHERE role_id = %s;" % row0[0][0])
            for i in range(len(row1)):
                menudate.append(row1[i][0])
        except:
            data = {
                "status": 0,
                "message": u"登录超时，请重新登陆!",
                "data": []
            }
            jsonstr = json.dumps(data)
            return HttpResponse(jsonstr, content_type="application/json")
        if 18 not in menudate:
            data = {
                "status": 0,
                "message": u"权限不够！",
                "data": []
            }
            jsonstr = json.dumps(data)
            return HttpResponse(jsonstr, content_type="application/json")
        # 多用户登录验证
        md5str = request.COOKIES['loginmd5']
        row0 = MySQLDB.SelectMySql("SELECT user_id FROM t_sys_user WHERE valid_md5 = '%s';" % md5str)
        try:
            if str(row0[0][0]) == userid:
                pass
            else:
                data = {
                    "status": 0,
                    "message": u"该账号在其他地方登录",
                    "data": []
                }
                jsonstr = json.dumps(data)
                return HttpResponse(jsonstr, content_type="application/json")
        except:
            data = {
                "status": 0,
                "message": u"其他错误",
                "data": []
            }
            jsonstr = json.dumps(data)
            return HttpResponse(jsonstr, content_type="application/json")
        return func(request)

    return jnner


# 巡检业务首页 页面
@auth
def QLXJ_XJYW_INDEX(request):
    return render(request, 'QLGL/XJYW/QLGL_XJYW_index.html', {})


# 定期检查首页 页面
@auth
def QLXJ_XJYW_DQJC_index(request):
    return render(request, 'QLGL/XJYW/DQJC.html', {})


# 功能：定期检查首页数据
# 传入参数：request
# 返回参数：response
@authjson
def QLXJ_XJYW_DQJC_index_data(request):
    datalist = []

    try:
        # 定期检查首页数据
        tp = request.GET["type"]
        if tp == "1":
            row = MySQLDB.SelectMySql(
                "SELECT check_id,bridge_id,bridge_name,bridge_code,check_depart,check_depart_name,user_charge_name, date_format(from_date,'%Y-%m-%d') as from_date, date_format(to_date,'%Y-%m-%d') as to_date ,score,grade,status from t_check where status <> 0 and type = 1 order by from_date desc;")
            key = ["check_id", "bridge_id", "bridge_name", "bridge_code", "check_depart", "check_depart_name",
                   "user_charge_name", "from_date", "to_date", "score", "grade", "status"]
        elif tp == "2":
            row = MySQLDB.SelectMySql(
                "SELECT check_id,bridge_id,bridge_name,bridge_code,check_depart,check_depart_name,user_charge_name,date_format(from_date,'%Y-%m-%d') as from_date, date_format(to_date,'%Y-%m-%d') as to_date ,(SELECT count(*) from t_check_record  where t_check_record.status = 1 and t_check_record.check_id = t_check.check_id) as disease,status from t_check  where status <> 0 and type = 2;")
            key = ["check_id", "bridge_id", "bridge_name", "bridge_code", "check_depart", "check_depart_name",
                   "user_charge_name", "from_date", "to_date", "disease", "status"]
        if len(row) > 0:

            for i in range(len(row)):
                info = {}
                for j in range(len(key)):
                    if key[j] == "score":
                        info[key[j]] = str(row[i][j])
                    else:
                        info[key[j]] = row[i][j]
                datalist.append(info)
        data = {
            "status": 1,
            "message": u"读取定期检查首页数据成功",
            "data": datalist
        }
    except Exception as e:
        data = {
            "status": 0,
            "message": u"读取定期检查首页数据失败",
            "data": []
        }
    return JsonResponse(data)


# 功能：选择责任单位之后再选择责任人
# 传入参数：request
# 返回参数：response
@authjson
def QLXJ_XJYW_DQJC_USER(request):
    organize_id = request.GET["organize_id"]
    userlist = []
    try:
        #
        row = MySQLDB.SelectMySql(
            "SELECT user_id,real_name from t_sys_user  where status = 1 and dept_id = '%s';" % organize_id)
        if len(row) > 0:
            key = ["user_id", "real_name"]
            for i in range(len(row)):
                info = {}
                for j in range(len(key)):
                    info[key[j]] = row[i][j]
                userlist.append(info)
        data = {
            "status": 1,
            "message": u"读取责任人成功",
            "data": userlist
        }
    except Exception as e:
        data = {
            "status": 0,
            "message": u"读取责任人数据失败",
            "data": []
        }
    return JsonResponse(data)


# 定期检查新增 页面
@auth
def QLXJ_XJYW_DQJC_add(request):
    user_id = request.COOKIES["userid"]
    bridgeInfo = []
    userInfo = []
    deptInfo = []
    organize_id = 0
    try:
        # 定期检查桥梁列表
        tp = request.GET["type"]
        row = MySQLDB.SelectMySql(
            "SELECT bridge_id,bridge_name from t_bridge_base where status=1;")
        if len(row) > 0:
            key = ["bridge_id", "bridge_name"]
            for i in range(len(row)):
                info = {}
                for j in range(len(key)):
                    info[key[j]] = row[i][j]
                bridgeInfo.append(info)
        row3= MySQLDB.SelectMySql(
            "SELECT dept_id from t_sys_user where user_id='%s' and status=1 ;"%(user_id))
        organize_id = row3[0][0]

        # 定期检查新增单位列表
        row2 = MySQLDB.SelectMySql(
            "SELECT organize_id,name from t_sys_organize where status = 1 and category=2;")
        if len(row2) > 0:
            key = ["organize_id", "name"]
            for i in range(len(row2)):
                info = {}
                for j in range(len(key)):
                    info[key[j]] = row2[i][j]
                deptInfo.append(info)
            # 经常检查新增用户列表
            row1 = MySQLDB.SelectMySql(
                "SELECT user_id,real_name from t_sys_user where status = 1 and dept_id=%s;" % row2[0][0] )
            if len(row1) > 0:
                key = ["user_id", "real_name"]
                for i in range(len(row1)):
                    info = {}
                    for j in range(len(key)):
                        info[key[j]] = row1[i][j]
                    userInfo.append(info)

    except Exception as e:
        bridgeInfo = []
        userInfo = []
        deptInfo = []
    return render(request, 'QLGL/XJYW/DQJC_ADD.html',
                  {"user_id": int(user_id), "bridgeInfo": bridgeInfo, "userInfo": userInfo, "deptInfo": deptInfo,
                   "type": tp,"organize_id":organize_id})


# 功能：定期检查新增保存
# 传入参数：request
# 返回参数：response
@authjson
def QLXJ_XJYW_DQJC_addsave(request):
    bridge_id = request.POST['bridge_id']
    bridge_name = request.POST['bridge_name']
    user_id = request.POST['user_id']
    real_name = request.POST['real_name']
    organize_id = request.POST['organize_id']
    name = request.POST['name']
    checkdate = request.POST['checkdate']
    tp = request.POST['type']
    try:
        # 定期检查首页
        row = MySQLDB.CommitMySql(
            "INSERT INTO `t_check`(`bridge_id`,`bridge_name`,`bridge_code`,`from_date`,`check_depart`,`check_depart_name`,`user_charge`,`user_charge_name`,`status`,`type`) select bridge_id,bridge_name,bridge_code,'%s','%s','%s','%s','%s',1,'%s' from t_bridge_base where bridge_id = '%s';" % (
                checkdate, organize_id, name, user_id, real_name, tp, bridge_id))
        data = {
            "status": 1,
            "message": u"新增保存成功",
            "data": []
        }
    except Exception as e:
        data = {
            "status": 0,
            "message": u"新增保存失败",
            "data": []
        }
    return JsonResponse(data)


# 定期检查修改 页面
@auth
def QLXJ_XJYW_DQJC_mod(request):
    check_id = request.GET['check_id']
    tp = request.GET['type']
    bridgeInfo = []
    userInfo = []
    deptInfo = []
    defaultInfo = []
    try:
        # 定期检查默认数据
        row4 = MySQLDB.SelectMySql(
            "SELECT bridge_id,check_depart,user_charge,date_format(from_date,'%%Y-%%m-%%d') as from_date from t_check where check_id = '%s';" % check_id)
        if len(row4) > 0:
            key = ["bridge_id", "check_depart", "user_charge", "from_date"]
            for i in range(len(row4)):
                info = {}
                for j in range(len(key)):
                    info[key[j]] = row4[i][j]
                defaultInfo.append(info)
        # 定期检查桥梁列表
        row = MySQLDB.SelectMySql(
            "SELECT bridge_id,bridge_name from t_bridge_base where status=1;")
        if len(row) > 0:
            key = ["bridge_id", "bridge_name"]
            for i in range(len(row)):
                info = {}
                for j in range(len(key)):
                    info[key[j]] = row[i][j]
                bridgeInfo.append(info)

        # 定期检查新增单位列表
        row2 = MySQLDB.SelectMySql(
            "SELECT organize_id,name from t_sys_organize where status = 1 and category=2;")
        if len(row2) > 0:
            key = ["organize_id", "name"]
            for i in range(len(row2)):
                info = {}
                for j in range(len(key)):
                    info[key[j]] = row2[i][j]
                deptInfo.append(info)
             # 经常检查新增用户列表
            row1 = MySQLDB.SelectMySql(
                "SELECT user_id,real_name from t_sys_user where status = 1 and dept_id=%s;" % row2[0][0] )
            if len(row1) > 0:
                key = ["user_id", "real_name"]
                for i in range(len(row1)):
                    info = {}
                    for j in range(len(key)):
                        info[key[j]] = row1[i][j]
                    userInfo.append(info)

    except Exception as e:
        bridgeInfo = []
        userInfo = []
        deptInfo = []
        defaultInfo = []
    return render(request, 'QLGL/XJYW/DQJC_MODIFY.html',
                  {"check_id": check_id, "defaultInfo": defaultInfo, "bridgeInfo": bridgeInfo, "userInfo": userInfo,
                   "deptInfo": deptInfo, "type": tp})


# 功能：定期检查修改保存
# 传入参数：request
# 返回参数：response
@authjson
def QLXJ_XJYW_DQJC_modsave(request):
    check_id = request.POST['check_id']
    tp = request.POST['type']
    user_id = request.POST['user_id']
    organize_id = request.POST['organize_id']
    checkdate = request.POST['checkdate']
    try:
        # 定期检查首页数据
        row = MySQLDB.CommitMySql(
            "UPDATE `t_check` set `from_date`= '%s',`check_depart`= '%s',`check_depart_name`=(select name from t_sys_organize where organize_id= '%s'),`user_charge`= '%s',`user_charge_name`=(select real_name from t_sys_user where user_id= '%s') where check_id = '%s';" % (
                checkdate, organize_id, organize_id, user_id, user_id, check_id))
        data = {
            "status": 1,
            "message": u"修改保存成功",
            "data": []
        }
    except Exception as e:
        data = {
            "status": 0,
            "message": u"修改保存失败",
            "data": []
        }
    return JsonResponse(data)


# 功能：定期检查删除
# 传入参数：request
# 返回参数：response
@authjson
def QLXJ_XJYW_DQJC_del(request):
    check_id = request.GET['check_id']
    try:
        # 定期检查首页数据
        row = MySQLDB.CommitMySql(
            "UPDATE t_check set status = 0 where check_id = '%s';" % (check_id))
        data = {
            "status": 1,
            "message": u"删除成功",
            "data": []
        }
    except Exception as e:
        data = {
            "status": 0,
            "message": u"删除失败",
            "data": []
        }
    return JsonResponse(data)


# 定期检查查看 页面
@auth
def QLXJ_XJYW_DQJC_SEE(request):
    check_id = request.GET['check_id']
    bridge_id = request.GET['bridge_id']
    tp = request.GET['type']
    return render(request, 'QLGL/XJYW/DQJC_SEE.html',
                  {"check_id": json.dumps(check_id), "bridge_id": json.dumps(bridge_id), "type": json.dumps(tp)})


# 功能：定期检查查看页面数据
# 传入参数：request
# 返回参数：response
@authjson
def QLXJ_XJYW_DQJC_SEE_DATA(request):
    check_id = request.GET['check_id']
    tp = request.GET['type']
    datalist = []
    try:
        # 定期检查查看页面数据
        row = MySQLDB.SelectMySql(
            "SELECT a.check_record_id,a.record_code,b.parts_name,disease_name,member_name,member_no,check_date,level,position,remark,description from t_check_record a inner join t_sys_parts b on b.parts_code = a.parts_code where a.status = 1 and a.check_id = '%s';" % (
                check_id))

        # select disease_id,disease_name,a.parts_code,parts_name,member_id,member_name,member_no,level,disease_scale_id,position,description,remark from t_check_record a inner join t_sys_parts b on a.parts_code = b.parts_code where check_record_id = '%s' and a.status = 1;
        if len(row) > 0:
            key = ["check_record_id", "record_code", "parts_name", "disease_name", "member_name", "member_no",
                   "check_date", "level", "position", "remark", "description"]
            for i in range(len(row)):
                info = {}
                for j in range(len(key)):
                    info[key[j]] = row[i][j]
                datalist.append(info)
        data = {
            "status": 1,
            "message": u"查看页面数据成功",
            "data": datalist
        }
    except Exception as e:
        data = {
            "status": 0,
            "message": u"查看页面数据失败",
            "data": []
        }
    return JsonResponse(data)


# 定期检查新增病害 页面
@auth
def QLXJ_XJYW_DQJC_DISEASE_ADD(request):
    check_id = request.GET['check_id']
    bridge_id = request.GET['bridge_id']
    tp = request.GET['type']
    # check_record_id = request.GET['check_record_id']
    PartsInfo = []
    try:
        row = Common.GetPartsListByBridge(bridge_id)
        if len(row) > 0:
            key = ["parts_no", "parts_code", "bridge_parts_name", "position_code", "param_bridge_type_code",
                   "bridge_parts_id"]
            for i in range(len(row)):
                info = {}
                for j in range(len(key)):
                    info[key[j]] = row[i][j]
                PartsInfo.append(info)
    except Exception as e:
        pass
    return render(request, 'QLGL/XJYW/DQJC_SEE_ADD.html',
                  {"check_id": check_id, "bridge_id": bridge_id, "PartsInfo": PartsInfo, "type": json.dumps(tp)})


# 功能：定期检查新增病害选择部件之后再选择构件
# 传入参数：request
# 返回参数：response
@authjson
def QLXJ_XJYW_DQJC_SEE_DATA_MEMBER(request):
    check_id = request.GET['check_id']
    bridge_id = request.GET['bridge_id']
    parts_code = request.GET['parts_code']
    MemberInfo = []
    try:
        row = MySQLDB.SelectMySql(
            "SELECT bridge_member_id,member_name,notes from t_bridge_member where bridge_id = '%s' and parts_code = '%s';" % (
                bridge_id, parts_code))
        if len(row) > 0:
            for m in range(len(row)):
                info = {}
                info["bridge_member_id"] = row[m][0]
                info["member_no"] = row[m][1]
                info["member_name"] = row[m][2]
                MemberInfo.append(info)
        data = {
            "status": 1,
            "message": u"查看页面数据成功",
            "data": MemberInfo
        }
    except Exception as e:
        data = {
            "status": 0,
            "message": u"查看页面数据失败",
            "data": []
        }
    return JsonResponse(data)


# 功能：定期检查新增选择部件后加载病害信息
# 传入参数：request
# 返回参数：response
@authjson
def QLXJ_XJYW_DQJC_SEE_DATA_DISEASE(request):
    memberId = request.GET['member_id']
    DiseaseInfo = []
    try:
        row1 = Common.GetDiseaseByMemberId(memberId)
        if len(row1) > 0:
            for m in range(len(row1)):
                info = {}
                info["disease_id"] = row1[m][0]
                info["disease_name"] = row1[m][1]
                DiseaseInfo.append(info)
        data = {
            "status": 1,
            "message": u"查看病害信息成功",
            "data": DiseaseInfo
        }
    except Exception as e:
        data = {
            "status": 0,
            "message": u"查看病害信息失败",
            "data": []
        }
    return JsonResponse(data)


# 功能：定期检查新增病害选择病害类型后请求标度
# 传入参数：request
# 返回参数：response
def QLXJ_XJYW_DQJC_DATA_LEVEL(request):
    disease_id = request.GET['disease_id']
    LevelInfo = []
    try:
        row2 = Common.GetDiseaseLevel(disease_id)
        if len(row2) > 0:
            for m in range(len(row2)):
                info = {}
                info["disease_scale_id"] = row2[m][0]
                info["level"] = row2[m][1]
                info["sumup"] = row2[m][2]
                LevelInfo.append(info)
        data = {
            "status": 1,
            "message": u"查看病害标度成功",
            "data": LevelInfo
        }
    except Exception as e:
        data = {
            "status": 0,
            "message": u"查看病害标度失败",
            "data": []
        }
    return JsonResponse(data)


# 定期检查病害位置弹窗 页面
@auth
def QLXJ_XJYW_DQJC_DISEASE_POSITION(request):
    member_id = request.GET.get('member_id', 0)
    disease_id = request.GET['disease_id']
    # record_id = request.GET['check_record_id']

    PositionInfo = []
    AttrInfo = []
    one = []
    two = []
    three = []
    four = []
    try:
        row = MySQLDB.SelectMySql(
            "SELECT b.id,b.name,b.remark from t_disease_attribute a inner join t_sys_attribute b on a.attribute_id = b.id and b.status = 1 where a.disease_id = '%s' and a.param_type = 5 order by orderby;" % disease_id)
        if len(row) > 0:
            key = ["id", "name", "remark"]
            for i in range(len(row)):
                info = {}
                for j in range(len(key)):
                    info[key[j]] = row[i][j]
                AttrInfo.append(info)
        row1 = Common.GetPositionByDisease(member_id, disease_id)
        if len(row1) > 0:
            for m in range(len(row1)):
                info = {}
                info["attr_id"] = row1[m][1]
                info["attr_name"] = row1[m][2]
                if (1 == row1[m][0]):
                    one.append(info)
                if (2 == row1[m][0]):
                    two.append(info)
                if (3 == row1[m][0]):
                    three.append(info)
                if (4 == row1[m][0]):
                    four.append(info)
                    # PositionInfo.append(info)
    except Exception as e:
        pass
    if len(one):
        info = {}
        info["type"] = "1"
        info["itme"] = one
        PositionInfo.append(info)
    if len(two):
        info = {}
        info["type"] = "2"
        info["itme"] = two
        PositionInfo.append(info)
    if len(three):
        info = {}
        info["type"] = "3"
        info["itme"] = three
        PositionInfo.append(info)
    if len(four):
        info = {}
        info["type"] = "4"
        info["itme"] = four
        PositionInfo.append(info)
    # return JsonResponse({"data":PositionInfo})
    return render(request, 'QLGL/XJYW/DQJC_SEE_ADD_POSITION.html',
                  {"PositionInfo": PositionInfo, "AttrInfo": AttrInfo, "disease_id": disease_id,
                   "member_id": member_id})


# 功能：定期检查病害位置选择之后保存
# 传入参数：request
# 返回参数：response
def QLXJ_XJYW_DQJC_DISEASE_POSITIONSAVE(request):
    check_record_id = request.POST.get('check_record_id', '')
    disease_id = request.POST.get('disease_id', '')
    bridge_member_id = request.POST.get('member_id', '')
    attrList = request.POST.get("attrList", "")
    attr = eval(attrList)
    try:
        for i in attr:
            row = MySQLDB.CommitMySql(
                "INSERT INTO `t_check_disease_attr`(`check_record_id`,`check_id`,`disease_id`,`attribute_id`,`attribute_code`,`attribute_name`,`attribute_value`,`param_type`,`member_no`,`parts_code`,`status`) select c.check_record_id,c.check_id,%s,a.id,a.code,a.name,'%s',a.param_type,b.member_name,b.parts_code,1 from t_sys_attribute a,t_bridge_member b,t_check_record c where a.id = %s and b.bridge_member_id = %s and c.check_record_id = %s;" % (
                    disease_id, i["value"], i["attr_id"], bridge_member_id, check_record_id))
        if (row != "ok"):
            raise Exception("病害位置保存失败")
        data = {
            "status": 1,
            "message": u"新增成功",
            "data": []
        }
    except Exception as e:
        data = {
            "status": 0,
            "message": u"新增失败:" + e.message,
            "data": []
        }
    return JsonResponse(data)


# 功能：定期检查病害记录保存
# 传入参数：request
# 返回参数：response
@authjson
def QLXJ_XJYW_DQJC_SAVE(request):
    userid = request.COOKIES.get("userid")
    # 接收参数
    checkId = request.POST.get('check_id', -1)
    diseaseId = request.POST.get('disease_id', -1)
    memberId = request.POST.get('member_id', -1)
    scaleId = request.POST.get('scale_id', -1)
    position = request.POST.get('position', '')
    description = request.POST.get('description', '')
    remark = request.POST.get('remark', '')
    attrList = request.POST.get("attrList", "")
    if len(attrList) > 0:
        attr = eval(attrList)
    photoList = request.POST.get("photoList", "")
    if len(photoList) > 0:
        photo = eval(photoList)
    try:
        recordCode = Common.GenDocNum("t_check_record", "1")  # 定检生成编号
        if len(recordCode) == 0:
            raise Exception(u"编号生成失败")
        # 保存CheckRecord
        row = MySQLDB.CommitMySql(
            "INSERT INTO `t_check_record`(`record_code`,`check_id`,`bridge_id`,`bridge_name`,`disease_id`,`disease_name`,`parts_code`,`member_id`,`member_name`,`member_no`,`check_date`,`level`,`max_level`,`disease_scale_id`,`status`,`position`,`description`,`remark`) select '%s',a.check_id,a.bridge_id,a.bridge_name,b.disease_id,b.disease_name,c.parts_code,c.bridge_member_id,c.notes,c.member_name,now(),d.level,(select max(level) from t_sys_disease_scale where disease_id = d.disease_id),d.disease_scale_id,1,'%s','%s','%s' from t_check a,t_sys_disease b,t_bridge_member c,t_sys_disease_scale d where a.check_id = '%s' and b.disease_id = '%s' and c.bridge_member_id = '%s' and d.disease_scale_id = '%s';" % (
                recordCode, position, description, remark, checkId, diseaseId, memberId, scaleId))
        if (row != "ok"):
            raise Exception(u"数据保存失败1")
        record = MySQLDB.SelectMySql(
            "select check_record_id from t_check_record where record_code = '%s';" % recordCode)
        if len(record) == 0:
            raise Exception(u"数据保存失败2")
        recordId = record[0][0]
        # 保存属性记录
        for i in attr:
            row = MySQLDB.CommitMySql(
                "INSERT INTO `t_check_disease_attr`(`check_record_id`,`check_id`,`disease_id`,`attribute_id`,`attribute_code`,`attribute_name`,`attribute_value`,`param_type`,`member_no`,`parts_code`,`status`) select c.check_record_id,c.check_id,%s,a.id,a.code,a.name,'%s',a.param_type,b.member_name,b.parts_code,1 from t_sys_attribute a,t_bridge_member b,t_check_record c where a.id = %s and b.bridge_member_id = %s and c.check_record_id = %s;" % (
                    diseaseId, i["attr_value"], i["attr_id"], memberId, recordId))
            if (row != "ok"):
                raise Exception(u"属性数据保存失败3")
        if len(photoList) > 0:
            for i in photo:
                insertFiles = "INSERT INTO `t_check_file`(`check_record_id`,`name`,`url`,`member_name`,`disease_name`,`status`,`type`) select '%s','%s','%s',a.member_name,b.disease_name,1,1 from t_bridge_member a,t_sys_disease b where a.bridge_member_id = %s and b.disease_id = %s;" % (
                    recordId, i["file_name"], i["file_url"], memberId, diseaseId)
                row = MySQLDB.CommitMySql(insertFiles)
                if (row != "ok"):
                    raise Exception(u"保存图片数据保存失败")
        data = {
            "status": 1,
            "message": u"新增成功",
            "data": []
        }
    except Exception as e:
        data = {
            "status": 0,
            "message": u"新增失败:" + e.message,
            "data": []
        }
    return JsonResponse(data)


@csrf_exempt
def QLXJ_XJYW_DQJC_ADD_UPLOADFILE(request):
    data = {
        "status": 0,
        "message": u"上传文件失败",
        "data": []
    }
    if request.method == "POST":
        myFile = request.FILES.getlist("myfile")
        # 上传文件
        data = FileUtil.UploadFiles(myFile)
    return JsonResponse(data)


# 功能：定期检查病害记录修改
# 传入参数：request
# 返回参数：response
@auth
def QLXJ_XJYW_DQJC_DISEASE_MOD(request):
    checkRecordId = request.GET.get("check_record_id", -1)
    checkRecordInfo = []
    diseaseInfo = []
    levelInfo = []
    attrInfo = []
    photoInfo = []

    try:
        row = MySQLDB.SelectMySql(
            "select disease_id,disease_name,a.parts_code,parts_name,member_id,member_name,member_no,level,disease_scale_id,position,description,remark from t_check_record a inner join t_sys_parts b on a.parts_code = b.parts_code where check_record_id = '%s' and a.status = 1;" % (
                checkRecordId))
        if len(row) > 0:
            key = ['disease_id', 'disease_name', 'parts_code', 'parts_name', 'member_id', 'member_name', 'member_no',
                   'level', 'disease_scale_id', 'position', 'description', 'remark']
            for i in range(len(row)):
                info = {}
                for j in range(len(key)):
                    info[key[j]] = row[i][j]
                checkRecordInfo.append(info)
            memberId = checkRecordInfo[0]["member_id"]
            diseaseId = checkRecordInfo[0]["disease_id"]
        else:
            raise Exception(u"病害信息错误")
        row = Common.GetDiseaseByMemberId(memberId)
        if len(row) > 0:
            for m in range(len(row)):
                info = {}
                info["disease_id"] = row[m][0]
                info["disease_name"] = row[m][1]
                diseaseInfo.append(info)
        row = Common.GetDiseaseLevel(diseaseId)
        if len(row) > 0:
            for m in range(len(row)):
                info = {}
                info["disease_scale_id"] = row[m][0]
                info["level"] = row[m][1]
                info["sumup"] = row[m][2]
                levelInfo.append(info)
        sqlCom = "select attribute_id,attribute_name,param_type,attribute_value from t_check_disease_attr where check_record_id = '%s' and status = 1;" % checkRecordId
        row = MySQLDB.SelectMySql(sqlCom)
        if len(row) > 0:
            for m in range(len(row)):
                info = {}
                info["attr_id"] = row[m][0]
                info["attr_name"] = row[m][1]
                info["type"] = row[m][2]
                info["attr_value"] = row[m][3]
                attrInfo.append(info)
        sqlCom = "select check_file_id,name,url from t_check_file where check_record_id = '%s' and status = 1;" % checkRecordId
        row = MySQLDB.SelectMySql(sqlCom)
        if len(row) > 0:
            for m in range(len(row)):
                info = {}
                info["file_id"] = row[m][0]
                info["file_name"] = row[m][1]
                info["file_url"] = row[m][2]
                photoInfo.append(info)

    except Exception as e:
        return e
    return render(request, 'QLGL/XJYW/DQJC_SEE_MODIFY.html',
                  {"check_record_id": json.dumps(checkRecordId), "checkRecordInfo": checkRecordInfo,
                   "diseaseInfo": diseaseInfo, "levelInfo": levelInfo, "attrInfo": json.dumps(attrInfo),
                   "photoInfo": photoInfo})


# 定期检查病害位置弹窗 页面
@auth
def QLXJ_XJYW_DQJC_DISEASE_POSITION1(request):
    member_id = request.GET.get('member_id', 0)
    disease_id = request.GET['disease_id']
    # record_id = request.GET['check_record_id']

    PositionInfo = []
    AttrInfo = []
    one = []
    two = []
    three = []
    four = []
    try:
        row = MySQLDB.SelectMySql(
            "SELECT b.id,b.name,b.remark from t_disease_attribute a inner join t_sys_attribute b on a.attribute_id = b.id and b.status = 1 where a.disease_id = '%s' and a.param_type = 5 order by orderby;" % disease_id)
        if len(row) > 0:
            key = ["id", "name", "remark"]
            for i in range(len(row)):
                info = {}
                for j in range(len(key)):
                    info[key[j]] = row[i][j]
                AttrInfo.append(info)
        row1 = Common.GetPositionByDisease(member_id, disease_id)
        if len(row1) > 0:
            for m in range(len(row1)):
                info = {}
                info["attr_id"] = row1[m][1]
                info["attr_name"] = row1[m][2]
                if (1 == row1[m][0]):
                    one.append(info)
                if (2 == row1[m][0]):
                    two.append(info)
                if (3 == row1[m][0]):
                    three.append(info)
                if (4 == row1[m][0]):
                    four.append(info)
                    # PositionInfo.append(info)
    except Exception as e:
        pass
    if len(one):
        info = {}
        info["type"] = "1"
        info["itme"] = one
        PositionInfo.append(info)
    if len(two):
        info = {}
        info["type"] = "2"
        info["itme"] = two
        PositionInfo.append(info)
    if len(three):
        info = {}
        info["type"] = "3"
        info["itme"] = three
        PositionInfo.append(info)
    if len(four):
        info = {}
        info["type"] = "4"
        info["itme"] = four
        PositionInfo.append(info)
    # return JsonResponse({"data":PositionInfo})
    return render(request, 'QLGL/XJYW/DQJC_SEE_MODIFY_POSITION.html',
                  {"PositionInfo": PositionInfo, "AttrInfo": AttrInfo, "disease_id": disease_id,
                   "member_id": member_id})


# 功能：定期检查病害记录修改保存
# 传入参数：request
# 返回参数：response
@authjson
def QLXJ_XJYW_DQJC_DISEASE_MODSAVE(request):
    # 接收参数
    checkRecordId = request.POST.get('check_record_id', -1)
    diseaseId = request.POST.get('disease_id', -1)
    memberId = request.POST.get('member_id', -1)
    scaleId = request.POST.get('scale_id', -1)
    position = request.POST.get('position', '')
    description = request.POST.get('description', '')
    remark = request.POST.get('remark', '')
    attrList = request.POST.get("attrList", "")
    if len(attrList) > 0:
        attr = eval(attrList)
    photoList = request.POST.get("photoList", "")
    if len(photoList) > 0:
        photo = eval(photoList)
    originalAttrIds = []
    originalFileIds = []
    try:
        # 保存CheckRecord
        updateCmd = "UPDATE `t_check_record` SET `disease_id` = '%s',`disease_name` = (select disease_name from t_sys_disease where disease_id = '%s'),`level` = (select level from t_sys_disease_scale where disease_scale_id = '%s'),`max_level` = (select max(level) from t_sys_disease_scale where disease_id = '%s'),`disease_scale_id` = '%s',`position` = '%s',`description` = '%s',`remark` = '%s',`update_date` = now() WHERE `check_record_id` = '%s';" % (
            diseaseId, diseaseId, scaleId, diseaseId, scaleId, position, description, remark, checkRecordId)
        row = MySQLDB.CommitMySql(updateCmd)
        if (row != "ok"):
            raise Exception(u"定期检查数据保存失败")
        # 保存属性记录,先判断是否更新，若更新，修改数据
        if len(attrList) > 0:
            # 判断是否更新，新增的insert，改变的del
            # 提取原有属性数据
            selCmd = "select attribute_id from t_check_disease_attr where check_record_id = '%s' and status = 1;" % checkRecordId
            row = MySQLDB.SelectMySql(selCmd)
            if len(row) > 0:
                originalAttrIds = [str(w[0]) for w in row]
            inAttrIds = [w["attr_id"] for w in attr]
            # 比较差集，新列表有的，原来没得的，定义为新增加
            insertIds = list(set(inAttrIds).difference(set(originalAttrIds)))
            if len(insertIds):
                for i in [w for w in attr if w["attr_id"] in insertIds]:
                    insertCmd = "INSERT INTO `t_check_disease_attr`(`check_record_id`,`check_id`,`disease_id`,`attribute_id`,`attribute_code`,`attribute_name`,`attribute_value`,`param_type`,`member_no`,`parts_code`,`status`) select c.check_record_id,c.check_id,%s,a.id,a.code,a.name,'%s',a.param_type,b.member_name,b.parts_code,1 from t_sys_attribute a,t_bridge_member b,t_check_record c where a.id = %s and b.bridge_member_id = %s and c.check_record_id = %s;" % (
                        diseaseId, i["attr_value"], i["attr_id"], memberId, checkRecordId)
                    row = MySQLDB.CommitMySql(insertCmd)
                    if row != "ok":
                        raise Exception("修改病害记录属性失败")
            # 比较差集，缺少的东西删除
            deleteIds = list(set(originalAttrIds).difference(set(inAttrIds)))
            if len(deleteIds):
                for i in deleteIds:
                    deleteCmd = "update t_check_disease_attr set status = 0,update_date=now() where check_record_id = '%s' and attribute_id = '%s';" % (
                        checkRecordId, i)
                    row = MySQLDB.CommitMySql(deleteCmd)
                    if row != "ok":
                        raise Exception("修改病害记录属性失败")
            for i in [w for w in attr if w["attr_id"] not in insertIds]:
                updateCmd = "update t_check_disease_attr set attribute_value = '%s',update_date=now() where check_record_id = '%s' and attribute_id = '%s';" % (
                    i["attr_value"], checkRecordId, i["attr_id"])
                row = MySQLDB.CommitMySql(updateCmd)
                if row != "ok":
                    raise Exception("修改病害记录属性失败")
        # 保存图片信息，存在2种情况：
        # 1、已有数据删除，需要把所有数据提取出来之后，不存在的数据移除；
        # 2、新增数据，插入数据库
        if len(photoList) > 0:
            # 提取原有数据
            selCmd = "select check_file_id from t_check_file where check_record_id = '%s' and status = 1;" % checkRecordId
            row = MySQLDB.SelectMySql(selCmd)

            if len(row) > 0:
                originalFileIds = [str(w[0]) for w in row]
            inFileIds = [w["file_id"] for w in photo]
            # 比较数据，原来有的，新的没有，判断被删除数据
            deleteIds = list(set(originalFileIds).difference(set(inFileIds)))
            if len(deleteIds) > 0:
                for i in deleteIds:
                    deleteCmd = "update t_check_file set status = 0,update_date=now() where check_file_id = '%s';" % i
                    row = MySQLDB.CommitMySql(deleteCmd)
                    if row != "ok":
                        raise Exception("修改病害记录图片失败")
            for i in [w for w in photo if w["file_id"] == "0"]:
                insertCmd = "INSERT INTO `t_check_file`(`check_record_id`,`name`,`url`,`member_name`,`disease_name`,`status`,`type`) select '%s','%s','%s',a.member_name,b.disease_name,1,1 from t_bridge_member a,t_sys_disease b where a.bridge_member_id = %s and b.disease_id = %s;" % (
                    checkRecordId, i["file_name"], i["file_url"], memberId, diseaseId)
                row = MySQLDB.CommitMySql(insertCmd)
                if row != "ok":
                    raise Exception("修改病害记录图片失败")
        data = {
            "status": 1,
            "message": u"新增成功",
            "data": []
        }
    except Exception as e:
        data = {
            "status": 0,
            "message": u"新增失败:" + e.message,
            "data": []
        }
    return JsonResponse(data)


# 功能：定期检查病害记录删除
# 传入参数：request
# 返回参数：response
@authjson
def QLXJ_XJYW_DQJC_DISEASE_DEL(request):
    checkRecordId = request.GET.get("check_record_id", -1)
    try:
        if checkRecordId > 0:
            delCmd = "update t_check_record set status = 0,update_date = now() where check_record_id = '%s';" % checkRecordId
            row = MySQLDB.CommitMySql(delCmd)
            if row != "ok":
                raise Exception(u"病害记录删除失败")
            data = {
                "status": 1,
                "message": u"病害记录删除成功",
                "data": []
            }
    except Exception as e:
        data = {
            "status": 0,
            "message": e.message,
            "data": []
        }
    return JsonResponse(data)


# 功能：查看定期检查病害记录媒体信息
# 传入参数：request
# 返回参数：response
@authjson
def QLXJ_XJYW_DQJC_DISEASE_MEDIA(request):
    checkRecordId = request.GET.get("check_record_id", -1)
    photoList = []
    try:
        if checkRecordId > 0:
            selCmd = "select check_file_id,name,url from t_check_file where check_record_id = '%s' and status = 1;" % checkRecordId
            row = MySQLDB.SelectMySql(selCmd)
            if len(row) > 0:
                for i in range(len(row)):
                    info = {}
                    item = row[i]
                    info["file_id"] = item[0]
                    info["file_name"] = item[1]
                    info["file_url"] = item[2]
                    photoList.append(info)
            data = {
                "status": 1,
                "message": u"查询成功",
                "data": photoList
            }
    except Exception as e:
        data = {
            "status": 0,
            "message": e.message,
            "data": []
        }
    return JsonResponse(data)


# 功能：定期检查病害记录移动
# 传入参数：request
# 返回参数：response
@auth
def QLXJ_XJYW_DQJC_DISEASE_MOVE(request):
    checkRecordId = request.GET.get("check_record_id", -1)
    checkRecordInfo = {}
    bridgeId = -1
    bridgeInfo = []
    partsInfo = []
    memberInfo = []
    try:
        selCmd = "select bridge_id,bridge_name,parts_code,member_id,member_name,member_no from t_check_record where check_record_id = '%s';" % checkRecordId
        row = MySQLDB.SelectMySql(selCmd)
        keys = ["bridge_id", "bridge_name", "parts_code", "member_id", "member_name", "member_no"]
        if len(row) > 0:
            i = 0
            for j in range(len(keys)):
                checkRecordInfo[keys[j]] = row[i][j]
        else:
            raise Exception(u"定期检查数据异常")
        # 桥梁信息
        selCmd = "select bridge_id,bridge_name from t_bridge_base where status = 1;"
        row = MySQLDB.SelectMySql(selCmd)
        if len(row) > 0:
            for i in range(len(row)):
                info = {}
                info["bridge_id"] = row[i][0]
                info["bridge_name"] = row[i][1]
                bridgeInfo.append(info)
        # 部件信息
        row = Common.GetPartsListByBridge(checkRecordInfo["bridge_id"])
        if len(row) > 0:
            for i in range(len(row)):
                info = {}
                info["parts_code"] = str(row[i][1])
                info["parts_name"] = row[i][2]
                partsInfo.append(info)
        # 构件信息
        selCmd = "SELECT bridge_member_id,member_name,notes from t_bridge_member where bridge_id = '%s' and parts_code = '%s' and status = 1;" % (
            checkRecordInfo["bridge_id"], checkRecordInfo["parts_code"])
        row = MySQLDB.SelectMySql(selCmd)
        if len(row) > 0:
            for m in range(len(row)):
                info = {}
                info["bridge_member_id"] = row[m][0]
                info["member_name"] = row[m][2]
                info["member_no"] = row[m][1]
                memberInfo.append(info)

    except Exception as e:
        pass
    return render(request, "QLGL/XJYW/DQJC_SEE_MOVE.html",
                  {"checkRecordId": checkRecordId, "checkRecordInfo": checkRecordInfo, "bridgeInfo": bridgeInfo,
                   "partsInfo": partsInfo, "memberInfo": memberInfo})


# 功能：根据桥梁信息返回对应部件列表
# 传入参数：request
# 返回参数：response
@authjson
def QLXJ_XJYW_DQJC_SEE_DATA_PARTS(request):
    bridgeId = request.GET.get("bridge_id", -1)
    partsList = []
    try:
        row = Common.GetPartsListByBridge(bridgeId)
        if len(row) < 1:
            raise Exception("桥梁未设定上部结构,没有部件信息")

        for i in range(len(row)):
            item = row[i]
            info = {}
            info["parts_code"] = item[1]
            info["parts_name"] = item[2]
            partsList.append(info)
        data = {
            "status": 1,
            "message": u"查询成功",
            "data": partsList
        }

    except Exception as e:
        data = {
            "status": 0,
            "message": e.message,
            "data": []
        }
    return JsonResponse(data)


# 功能：病害移动保存
# 传入参数：request
# 返回参数：response
@authjson
def QLXJ_XJYW_DQJC_DISEASE_MOVESAVE(request):
    checkRecordId = request.GET.get("check_record_id", -1)
    bridgeId = request.GET.get("bridge_id", -1)
    memberId = request.GET.get("member_id", -1)
    checkId = 0
    checkRecordInfo = {}
    try:
        if checkRecordId > 0:
            selCmd = "select bridge_id,member_id from t_check_record where check_record_id = '%s';" % checkRecordId
            row = MySQLDB.SelectMySql(selCmd)
            keys = ["bridge_id", "member_id"]
            if len(row) > 0:
                i = 0
                for j in range(len(keys)):
                    checkRecordInfo[keys[j]] = str(row[i][j])
            else:
                raise Exception(u"定期检查数据异常")
            # 检查选择桥梁是否有检测数据，若没有，则提示用户新增检测
            selCmd = "select check_id from t_check where bridge_id = '%s';" % bridgeId
            row = MySQLDB.SelectMySql(selCmd)
            if len(row) > 0:  # 存在检测记录
                checkId = row[0][0]
            else:
                raise Exception("所选桥梁没有定期检查数据，请先建立桥梁定期检查数据.")
            # 比较数据
            # 比较桥梁信息是否修改
            # update t_check_record a,t_bridge_base b,t_bridge_member c set a.bridge_id = b.bridge_id,a.bridge_name =b.bridge_name,a.parts_code = c.parts_code,a.member_id = c.bridge_member_id,a.member_name=c.notes,a.member_no=c.member_name where a.check_record_id = 5 and b.bridge_id = 4 and c.bridge_member_id = 82;
            updateCmdHand = "update t_check_record a "
            updateCmdSet = "set a.update_date = now() "
            updateCmdWhere = " where a.check_record_id='%s' " % checkRecordId
            updateFlag = 0
            if bridgeId != checkRecordInfo["bridge_id"]:
                # 更新桥梁信息
                updateFlag = 1
                updateCmdHand += ",t_bridge_base b "
                updateCmdSet += ",a.bridge_id = b.bridge_id,a.bridge_name =b.bridge_name,a.check_id = '%s' " % checkId
                updateCmdWhere += " and b.bridge_id = '%s' " % bridgeId
            if memberId != checkRecordInfo["member_id"]:
                # 更新构件信息
                updateFlag = 1
                updateCmdHand += ",t_bridge_member c "
                updateCmdSet += ",a.parts_code = c.parts_code,a.member_id = c.bridge_member_id,a.member_name=c.notes,a.member_no=c.member_name "
                updateCmdWhere += " and c.bridge_member_id = '%s' " % memberId
            if updateFlag > 0:
                # 执行更新
                updateCmd = updateCmdHand + updateCmdSet + updateCmdWhere
                row = MySQLDB.CommitMySql(updateCmd)
                if row != "ok":
                    raise Exception("数据更新失败")

        else:
            raise Exception(u"记录编号不存在")
        data = {
            "status": 1,
            "message": u"修改成功",
            "data": []
        }
    except Exception as e:
        data = {
            "status": 0,
            "message": e.message,
            "data": []
        }
    return JsonResponse(data)


# 功能：桥梁定检评分
# 传入参数：request
# 返回参数：response
@authjson
def QLXJ_XJYW_DQJC_SCORE(request):
    checkId = request.GET.get("check_id", -1)
    # todo 评分时，更改桥梁状态为已完成
    try:
        if checkId < 1:
            raise Exception(u"定检数据错误")
        # todo 验证桥梁1、是否存在评分单元，不存在平分单元不得评分；2、所有构件是否已选择在评分单元中，若存在未包含在评分单元中的构件，弹出提示，中断过程

        # todo 计算桥梁评分

        # 更改记录状态为3已完成
        updateCmd = "update t_check set status=3,update_date=now() where check_id = '%s';" % checkId
        row = MySQLDB.CommitMySql(updateCmd)
        if row != 'ok':
            raise Exception(u"桥梁评分失败")
        data = {
            "status": 1,
            "message": u"桥梁评分成功",
            "data": []
        }
    except Exception as e:
        data = {
            "status": 0,
            "message": e.message,
            "data": []
        }
    return JsonResponse(data)


# 功能：桥梁定检原始记录
# 传入参数：request
# 返回参数：response
@authjson
def QLXJ_XJYW_DQJC_ORIGRS(request):
    checkId = request.GET.get("check_id", -1)
    try:
        data = {
            "status": 1,
            "message": u"修改成功",
            "data": []
        }
    except Exception as e:
        data = {
            "status": 0,
            "message": e.message,
            "data": []
        }
    return JsonResponse(data)


# 功能：桥梁定检重新评分
# 传入参数：request
# 返回参数：response
@authjson
def QLXJ_XJYW_DQJC_RESCORE(request):
    checkId = request.GET.get("check_id", -1)
    # todo 重新计算分数
    try:
        data = {
            "status": 1,
            "message": u"修改成功",
            "data": []
        }
    except Exception as e:
        data = {
            "status": 0,
            "message": e.message,
            "data": []
        }
    return JsonResponse(data)


# 功能：桥梁定检重置评分
# 传入参数：request
# 返回参数：response
@authjson
def QLXJ_XJYW_DQJC_RESETSCORE(request):
    checkId = request.GET.get("check_id", -1)
    # todo 更改记录状态为进行中，并将分数清除，pad端可进行操作
    try:
        if checkId < 1:
            raise Exception(u"定检数据错误")
        # 更改记录状态为2进行中
        updateCmd = "update t_check set status=2,update_date=now() where check_id = '%s';" % checkId
        row = MySQLDB.CommitMySql(updateCmd)
        if row != 'ok':
            raise Exception(u"桥梁定检重置评分失败")
        data = {
            "status": 1,
            "message": u"桥梁定检重置评分成功",
            "data": []
        }
    except Exception as e:
        data = {
            "status": 0,
            "message": e.message,
            "data": []
        }
    return JsonResponse(data)


# 功能：桥梁定检导出报告
# 传入参数：request
# 返回参数：response
@authjson
def QLXJ_XJYW_DQJC_EXPORT(request):
    checkId = request.GET.get("check_id", -1)
    try:
        data = {
            "status": 1,
            "message": u"修改成功",
            "data": []
        }
    except Exception as e:
        data = {
            "status": 0,
            "message": e.message,
            "data": []
        }
    return JsonResponse(data)


# 功能：桥梁定检查看详情
# 传入参数：request
# 返回参数：response
@auth
def QLXJ_XJYW_DQJC_SCOREDETAIL(request):
    checkId = request.GET.get("check_id", -1)
    try:
        # todo 查看桥梁评分详情
        data = {
            "status": 1,
            "message": u"修改成功",
            "data": []
        }
    except Exception as e:
        data = {
            "status": 0,
            "message": e.message,
            "data": []
        }
    return render(request, "QLGL/XJYW/DQJC_DETAILS.html", {})


# 功能：桥梁定检查看部件详情
# 传入参数：request
# 返回参数：response
@authjson
def QLXJ_XJYW_DQJC_SCOREDETAIL_PARTS(request):
    checkId = request.GET.get("check_id", -1)
    try:
        # todo 查看桥梁部件评分详情
        data = {
            "status": 1,
            "message": u"修改成功",
            "data": []
        }
    except Exception as e:
        data = {
            "status": 0,
            "message": e.message,
            "data": []
        }
    return render(request, "", {})


# 经常检查首页 页面
@auth
def QLXJ_XJYW_JCJC_index(request):
    return render(request, 'QLGL/XJYW/JCJC.html', {})


# 功能：巡查组日常任务
# 传入参数：request
# 返回参数：response
@auth
def QLXJ_XJYW_RCJC(request):
    return render(request, "QLGL/XJYW/RCJC.html", {})


# 待处理任务查询数据
# 输入参数：request
# 返回参数：response
@authjson
def getDCLJson(request):
    data = {
        "status": 0,
        "message": u"查询失败",
        "data": []
    }

    try:
        userid = request.COOKIES['userid']
        row = MySQLDB.SelectMySql("call PendingTasks(%s) ;" % userid)

        alist = []

        if len(row) > 0:
            key = ["id", "assign_id", "task_id", "role_code", "category", "content", "status", "status_name", "type",
                   "type_name"]
            for i in range(len(row)):
                info = {}
                for j in range(len(key)):
                    info[key[j]] = row[i][j]
                alist.append(info)

        data = {
            "status": 1,
            "message": u"查询成功",
            "data": alist
        }

    except:
        pass
    jsonstr = json.dumps(data)
    return HttpResponse(jsonstr, content_type="application/json")


# 检查任务天气情况
# 如果不需填写，跳至日常巡查页面
def CheckWeather(request, taskid):
    # md5 = request.COOKIES['loginmd5']
    # md5row = MySQLDB.SelectMySql("SELECT * FROM t_sys_user WHERE description='%s';" % md5)
    # try:
    #     if len(md5row)>0:
    #         pass
    #     else:
    #         response = render_to_response('login.html', {})
    #         return response
    # except:
    #     response = render_to_response('login.html', {})
    #     return response
    # b = request.COOKIES['powerid']
    # date = []
    # date = PowerID.PowerID(int(b))
    # DCLpower = 0
    # if date[0] == 1 or date[1] == 1 or date[2] == 1:
    #     DCLpower = 1

    tasktq = taskWeather(taskid)
    # data = {"d":int(tasktq[0]['hasData'])>0}
    if int(tasktq[0]['hasData']) > 0:
        return RCJC(request, taskid, tasktq[0]['weather'], tasktq[0]['temperature'])
    return render(request, 'QLGL/XJYW/RCJC_XC_WEATHER.html', {'taskid': taskid})


def taskWeather(taskid):
    alist = []
    try:
        row = MySQLDB.SelectMySql("call taskWeather(%s);" % taskid)

        if len(row) > 0:
            for i in range(len(row)):
                info = {}
                info["hasData"] = row[i][0]
                info["weather"] = row[i][1]
                info["temperature"] = row[i][2]
                alist.append(info)

    except:
        pass

    return alist


def selDCItems():
    alist = []
    try:
        row = MySQLDB.SelectMySql(
            "SELECT param_id,param_name,param_code,parent_id,status,orderby,create_date,update_date FROM t_sys_param a where exists (SELECT 1 FROM t_sys_param b where b.param_code = 'dailycheckitem' and a.parent_id = b.param_id) order by orderby;")

        if len(row) > 0:
            for i in range(len(row)):
                info = {}
                info["id"] = row[i][0]
                info["name"] = row[i][1]
                alist.append(info)

    except:
        pass
    return alist


# 根据taskid判断任务类别
# 如果为跟踪任务，位置和病害不需填写；
def CheckTaskDisease(taskid):
    try:
        row = MySQLDB.SelectMySql(
            "select a.urgency_level,a.param_partol_id,c.param_name,a.disease_id,a.disease_name,a.pile_direction,a.pile_km,a.pile_m from t_dc_task_disease a left join t_dc_assign b on a.task_disease_id = b.task_disease_id  left join t_sys_param c on a.param_partol_id = c.param_id where b.task_id = %s and type=3;" % taskid)

        alist = []

        if len(row) > 0:
            for i in range(len(row)):
                info = {}
                info["urgency_level"] = row[i][0]
                info["param_partol_id"] = row[i][1]
                info["param_name"] = row[i][2]
                info["disease_id"] = row[i][3]
                info["disease_name"] = row[i][4]
                info["pile_direction"] = row[i][5]
                info["pile_km"] = row[i][6]
                info["pile_m"] = row[i][7]

                alist.append(info)

    except Exception as e:
        return HttpResponse(e)
    return alist


def RCJC(request, taskid, weather, temperature):
    # md5 = request.COOKIES['loginmd5']
    # md5row = MySQLDB.SelectMySql("SELECT * FROM t_sys_user WHERE description='%s';" % md5)
    # try:
    #     if len(md5row)>0:
    #         pass
    #     else:
    #         response = render_to_response('login.html', {})
    #         return response
    # except:
    #     response = render_to_response('login.html', {})
    #     return response
    # b = request.COOKIES['powerid']
    # date = []
    # date = PowerID.PowerID(int(b))
    # DCLpower = 0
    # if date[0] == 1 or date[1] == 1 or date[2] == 1:
    #     DCLpower = 1

    dailycheckitems = selDCItems()
    diseaseinfo = CheckTaskDisease(taskid)
    # response = render_to_response('XCZ/RCJC.html', {'taskid':taskid,'tasktq':json.dumps(tasktq),'dcitems':dailycheckitems})
    return render(request, 'QLGL/XJYW/RCJC_XC_RCJC.html',
                  {'taskid': taskid, 'dcitems': dailycheckitems, 'weather': weather, 'temperature': temperature,
                   'diseaseinfo': json.dumps(diseaseinfo)})
    # jsonstr = json.dumps(diseaseinfo)
    # return HttpResponse(jsonstr, content_type="application/json")
    # return response


def checkItemDetailJson(request):
    data = {
        "status": 0,
        "message": u"查询失败",
        "data": []
    }
    itemid = request.GET['cid']

    try:
        row = MySQLDB.SelectMySql(
            "select b.disease_id,disease_name from t_disease_checkitem a left join t_sys_disease b on a.disease_id = b.disease_id where param_dailycheck_id = %s and status = 1 order by b.orderby asc;" % itemid)
        alist = []

        if len(row) > 0:
            for i in range(len(row)):
                info = {}
                info["disease_id"] = row[i][0]
                info["disease_name"] = row[i][1]
                alist.append(info)
        data = {
            "status": 1,
            "message": u"查询成功",
            "data": alist
        }

    except Exception as e:
        return HttpResponse(e)
    return JsonResponse(data)


# 功能：文件上传
# 输入参数：request
# 返回参数：response
@csrf_exempt
def uploadFile_XC(request):
    message = u"上传成功"
    status = 1
    userdata = []
    if request.method == "POST":
        myFile = request.FILES.getlist("myfile")
        if not myFile:
            return HttpResponse("no files for upload!")
        # 存储文件
        userid = str(request.COOKIES['userid'])
        try:
            for f in myFile:
                d1 = datetime.datetime.now()
                d2 = d1 + datetime.timedelta(hours=8)
                locatime = d2.strftime("%Y-%m-%d %X")
                sjc = d2.strftime("%Y-%m-%d-%H-%M-%S")
                fName = sjc + '-' + f.name
                try:
                    destination = open(os.path.join("static/upfile/", fName), 'w+')
                    for chunk in f.chunks():
                        destination.write(chunk)
                    destination.close()
                except Exception as e:
                    print "=====>"+str(e)
                # return HttpResponse("ok")
                try:
                    # 生成MD5
                    DirStrMD5 = 'static/upfile/'
                    DirMD5 = DirStrMD5 + fName
                    a_file = open(DirMD5, 'rb')
                    m = hashlib.md5(a_file.read())
                    a_file.close()
                    hashMD5 = m.hexdigest()
                    # 存储数据库数据准备
                    tname = fName
                    tmpName = tname.split('.', 1)
                    filename = tmpName[0]
                    filetype = tmpName[1]
                    fileurl = '/static/upfile/' + tname
                    DirMD5xx = 'static/upfile/' + fileurl
                    filesize = getDocSize(DirMD5xx)
                    absfiledir = DirStrMD5
                    row = MySQLDB.CommitMySql(
                        "INSERT INTO `t_dc_task_disease_file` (`create_user`,`name`,`status`,`description`,`url`) VALUES ('%s', '%s', 1, '%s', '%s')" % (
                            userid, filename, filesize, fileurl))
                    # 获取ID
                    row = MySQLDB.SelectMySql(
                        "SELECT `task_disease_file_id` FROM `t_dc_task_disease_file` WHERE name='%s' and create_user='%s';" % (
                            filename, userid))
                    IDnum = row[0][0]
                    # 数据打包
                    info = {}
                    info["file_id"] = IDnum
                    info["file_url"] = fileurl
                    userdata.append(info)
                except Exception as e:
                    # return HttpResponse(e)
                    message = u"上传失败"
                    status = 0
                    userdata = []
        except Exception as e:
            status = 0
            message = str(e)
            userdata = []
        Sdata = {
            "status": status,
            "message": message,
            "data": userdata
        }
        jsonstr = json.dumps(Sdata)
        return HttpResponse(jsonstr, content_type="application/json")

        # a = 1
        # response = render_to_response('app_DQJC.html', {'flag': json.dumps(a)})
        # return response


# 获取文件大小
def formatSize(bytes):
    try:
        bytes = float('%.2f' % bytes)
        kb = bytes / 1024
        return float('%.2f' % kb)
    except:
        return 0


def getDocSize(path):
    try:
        size = os.path.getsize(path)
        return formatSize(size)
    except:
        return 0


# 保存病害记录
def DCSave(request):
    data = {
        "status": 0,
        "message": u"更新失败",
        "data": []
    }
    userid = str(request.COOKIES['userid'])
    try:
        alist = []
        taskid = request.POST['txtTaskId']
        code = Common.GenDocNum("t_dc_task", "1")  # 生成编号
        weather = request.POST['txtWeather']
        temperature = request.POST['txtTemperature']
        # weather=str(request.COOKIES['weather'])
        # temperature=int(request.COOKIES["temperature"])
        checkitem = request.POST['selCheckItem']
        disease = request.POST['selDisease']
        remark = request.POST['txtRemark']
        # urgencylevel = request.POST['urgencylevel']
        urgencylevel = ""
        if request.POST.has_key('urgencylevel'):
            urgencylevel = request.POST['urgencylevel']
        else:
            urgencylevel = request.POST['hidurgencylevel']
        piledirection = request.POST['selPileDirection']
        pilekm = ""
        if request.POST.has_key('btnpilekm'):
            pilekm = request.POST['btnpilekm']
        else:
            pilekm = request.POST['hidpilekm']
        pilem = ""
        if request.POST.has_key('btnpilem'):
            pilem = request.POST['btnpilem']
        else:
            pilem = request.POST['hidpilem']

        fileids = request.POST['txtFileId']
        # 默认类型为巡查任务状态为1，维护任务，状态为2
        tasktype = request.POST['hidtasktype']
        # 默认巡查任务，111 病害录入；如果是维护任务，121 病害追踪
        processCode = "111"
        if tasktype == "2":
            processCode = "121"

        row = MySQLDB.CommitMySql(
            "INSERT INTO t_dc_task_disease (task_id,code,weather,temperature,urgency_level,param_partol_id,disease_id,disease_name,pile_direction,pile_km,pile_m,remark,create_user,param_process_code) select %s,'%s','%s','%s',%s,%s,disease_id,disease_name,'%s',%s,%s,'%s','%s','%s' from t_sys_disease where disease_id = %s;" % (
                taskid, code, weather, temperature, urgencylevel, checkitem, piledirection, pilekm, pilem, remark,
                userid,
                processCode, disease));

        # 获取ID
        row = MySQLDB.SelectMySql(
            "SELECT task_disease_id FROM t_dc_task_disease WHERE task_id = %s and code = '%s';" % (taskid, code))
        IDnum = row[0][0]

        # 存储病害-文件关联信息
        if len(fileids) > 0:
            updataSql = ""
            temp = fileids.split('|')
            for t in temp:
                if len(t) > 0:
                    # updataSql.join("UPDATE `t_dc_task_disease_file` SET `task_disease_id` = %s WHERE `task_disease_file_id` = %s;"% (IDnum,t))
                    MySQLDB.CommitMySql(
                        "UPDATE `t_dc_task_disease_file` SET `task_disease_id` = %s WHERE `task_disease_file_id` = %s;" % (
                            IDnum, t))
        data = {
            "status": 1,
            "message": u"更新成功",
            "data": []
        }

    except Exception as e:
        return HttpResponse(e)
    return JsonResponse(data)


# 保存天气信息
def weatherSave_XC(request):
    userid = str(request.COOKIES['userid'])
    data = {
        "status": 0,
        "message": u"更新失败",
        "data": []
    }
    taskid = request.GET['tid']
    weather = request.GET['w']  # 测试是否能够接收到前端发来的input字段
    temperature = request.GET['t']
    try:
        row = MySQLDB.CommitMySql(
            "UPDATE t_dc_task SET task_date = ifnull(task_date,now()),weather = ifnull(weather,'%s'),temperature = ifnull(temperature,'%s'),update_user = %s,update_date = now() WHERE task_id=%s;" % (
                weather, temperature, userid, taskid))

        row1 = MySQLDB.CommitMySql(
            "UPDATE t_dc_assign set receive_date = ifnull(receive_date,now()),status = 2 WHERE task_id = %s;" % (
                taskid))
        data = {
            "status": 1,
            "message": u"更新成功",
            "data": []
        }

    except Exception as e:
        return HttpResponse(e)
    return JsonResponse(data)


def RCJC1(request, taskid):
    # taskid = request.GET.get("taskid")
    weather = request.GET.get("weather")
    temperature = request.GET.get("temperature")
    return RCJC(request, taskid, weather, temperature)


# 巡查组处理完成任务
# 输入参数：request,taskid
# 返回参数：response

def writeDCLXC(request):
    # md5 = request.COOKIES['loginmd5']
    # md5row = MySQLDB.SelectMySql("SELECT * FROM t_sys_user WHERE description='%s';" % md5)
    # try:
    #     if len(md5row)>0:
    #         pass
    #     else:
    #         data = {
    #         "status":3,
    #         "message":u"请重新登陆！",
    #         "data":[]
    #         }
    # except:
    #     data = {
    #         "status":3,
    #         "message":u"请重新登陆！",
    #         "data":[]
    #         }
    taskid = request.GET['taskid']
    # assignid = request.GET['assignid']
    userid = request.COOKIES['userid']
    user = int(userid)
    try:
        locatime = time.strftime("%Y-%m-%d %X", time.localtime())

        row = MySQLDB.SelectMySql(
            "SELECT  `assign_id`, `task_id`, `category`, `type`, `content`, `assign_user`, `assign_date`, `receive_user`, `receive_dept`, `receive_role_code`, `receive_date`, `complate_date`, `status`, `operation_process`, `from_id`, `from_type`, `task_disease_id` FROM `t_dc_assign` WHERE task_id='%s' ;" % taskid)  # 查询该任务安排表具体信息

        # 校验是否已经提交过该任务
        if row[0][12] == 3:
            data = {
                "status": 2,
                "message": u"该任务已提交过！",
                "data": []
            }
        else:
            MySQLDB.CommitMySql(
                "UPDATE `t_dc_assign` SET status=3,complate_date='%s',param_process_code = case type when 1 then '101' when 3 then '124' end WHERE task_id='%s';" % (
                    locatime, taskid))  # 改变任务安排表状态
            MySQLDB.CommitMySql(
                "UPDATE `t_dc_task` SET status=2,update_user='%s' ,update_date='%s' WHERE task_id='%s';" % (
                    user, locatime, taskid))  # 改变任务表状态

            row1 = MySQLDB.SelectMySql(
                "SELECT  `assign_id`, `task_id`, `category`, `type`, `content`, `assign_user`, `assign_date`, `receive_user`, `receive_dept`, `receive_role_code`, `receive_date`, `complate_date`, `status`, `operation_process`, `from_id`, `from_type`, `task_disease_id` FROM `t_dc_assign` WHERE task_id='%s' ;" % taskid)  # 查询该任务安排表具体信息，后面用到
            # 病害追踪任务
            if row1[0][3] == 3:
                MySQLDB.CommitMySql(
                    "INSERT INTO `t_dc_assign` (`category`, `type`, `content`, `assign_user`, `assign_date`,  `receive_role_code`, `status`, `from_id`, `from_type`, `task_disease_id`) VALUES (2,3,'%s','%s','%s','%s','%s','%s','%s','%s');" % (
                        row1[0][4], user, locatime, 'technology', 1, row1[0][1], 1, row1[0][16]))  # 生成处理任务安排
            # 巡查任务
            elif row1[0][3] == 1:
                MySQLDB.CommitMySql(
                    "INSERT INTO `t_dc_assign` (`category`, `type`, `content`, `assign_user`, `assign_date`, `receive_role_code`,  `status`, `from_id`, `from_type`) VALUES (1,1,'%s','%s','%s','%s','%s','%s','%s');" % (
                        u"大桥巡查完成", user, locatime, 'technology', 1, row1[0][1], 1))  # 生成通知任务安排

                row2 = MySQLDB.SelectMySql(
                    "SELECT `task_disease_id`, `task_id`, `code`, `weather`, `temperature`, `urgency_level`, (select param_name from t_sys_param where t_sys_param.param_id = t_dc_task_disease.param_partol_id), `disease_id`, `disease_name`, `pile_direction`, `pile_km`, `pile_m`, `remark`, `create_user`, `create_date`, `update_user`, `update_date` FROM `t_dc_task_disease` WHERE  task_id='%s' ;" % taskid)  # 查询该任务对应的病害信息

                for i in range(len(row2)):
                    MySQLDB.CommitMySql(
                        "INSERT INTO `t_dc_assign` (`category`, `type`, `content`, `assign_user`, `assign_date`,  `receive_role_code`, `status`, `from_id`, `from_type`, `task_disease_id`) VALUES (2,2,'%s','%s','%s','%s','%s','%s','%s','%s');" % (
                            str(row2[i][6]) + '-' + str(row2[i][8]), user, locatime, 'technology', 1, row2[i][0], 2,
                            row2[i][0]))  # 生成处理任务安排

            data = {
                "status": 1,
                "message": u"任务完成提交成功",
                "data": []
            }

    except Exception as e:
        data = {
            "status": 0,
            "message": str(e),
            "data": []
        }
    jsonstr = json.dumps(data)
    return HttpResponse(jsonstr, content_type="application/json")


def RW(request):
    # md5 = request.COOKIES['loginmd5']
    # md5row = MySQLDB.SelectMySql("SELECT * FROM t_sys_user WHERE description='%s';" % md5)
    # try:
    #     if len(md5row)>0:
    #         pass
    #     else:
    #         response = render_to_response('login.html', {})
    #         return response
    # except:
    #     response = render_to_response('login.html', {})
    #     return response
    # b = request.COOKIES['powerid']
    # date = []
    # date = PowerID.PowerID(int(b))
    # DCLpower = 0
    # if date[0] == 1 or date[1] == 1 or date[2] == 1:
    #     DCLpower = 1

    taskid = request.GET.get("taskid")
    tasktq = taskWeather(taskid)
    # data = {"d":int(tasktq[0]['hasData'])>0}
    if int(tasktq[0]['hasData']) > 0:
        return RWDetail(request, taskid, tasktq[0]['weather'], tasktq[0]['temperature'])
    return render(request, 'QLGL/XJYW/RCJC_WH_WEATHER.html', {'taskid': taskid})
    # return response


def RWDetail(request, taskid, weather, temperature):
    # md5 = request.COOKIES['loginmd5']
    # md5row = MySQLDB.SelectMySql("SELECT * FROM t_sys_user WHERE description='%s';" % md5)
    # try:
    #     if len(md5row)>0:
    #         pass
    #     else:
    #         response = render_to_response('login.html', {})
    #         return response
    # except:
    #     response = render_to_response('login.html', {})
    #     return response
    # b = request.COOKIES['powerid']
    # date = []
    # date = PowerID.PowerID(int(b))
    # DCLpower = 0
    # if date[0] == 1 or date[1] == 1 or date[2] == 1:
    #     DCLpower = 1
    # 取得当前维护任务来源病害信息
    diseaseinfo = DiseaseInfoByWH(taskid)
    return render(request, 'QLGL/XJYW/RCJC_WH_WHJL.html',
                  {'taskid': taskid, 'diseaseinfo': json.dumps(diseaseinfo), 'weather': weather,
                   'temperature': temperature})
    # return response


def DiseaseInfoByWH(taskid):
    alist = []
    try:
        row = MySQLDB.SelectMySql(
            "select case a.urgency_level when 1 then '另处' when 2 then '一般' when 3 then '紧急' end as urgency_level,c.param_name,a.disease_name,a.pile_direction,a.pile_km,a.pile_m,c.param_id,a.disease_id,urgency_level from t_dc_task_disease a left join t_dc_assign b on a.task_disease_id = b.task_disease_id left join t_sys_param c on a.param_partol_id = c.param_id where b.task_id = %s;" % taskid)

        if len(row) > 0:
            for i in range(len(row)):
                info = {}
                info["urgency"] = str(row[i][0])
                info["checkItem"] = str(row[i][1])
                info["disease_name"] = str(row[i][2])
                info["pile_direction"] = str(row[i][3])
                info["pile_km"] = int(row[i][4])
                info["pile_m"] = int(row[i][5])
                info["param_id"] = int(row[i][6])
                info["disease_id"] = int(row[i][7])
                info["urgency_level"] = int(row[i][8])
                alist.append(info)
                # alist.append({})
    except Exception as e:
        return HttpResponse(e)
    return alist


# 保存天气信息
def weatherSave_WH(request):
    data = {
        "status": 0,
        "message": u"更新失败",
        "data": []
    }
    taskid = request.GET['tid']
    weather = request.GET['w']  # 测试是否能够接收到前端发来的input字段
    temperature = request.GET['t']
    try:
        row = MySQLDB.CommitMySql(
            "UPDATE t_dc_task SET task_date = ifnull(task_date,now()),weather = ifnull(weather,'%s'),temperature = ifnull(temperature,'%s') WHERE task_id = %s;" % (
                weather, temperature, taskid))
        data = {
            "status": 1,
            "message": u"更新成功",
            "data": []
        }

    except Exception as e:
        return HttpResponse(e)
    return JsonResponse(data)


# 检查记录
def JCJL(request):
    taskid = request.GET.get("tid")
    weather = request.GET.get("w")
    temperature = request.GET.get("t")
    return RWDetail(request, taskid, weather, temperature)


# 保存病害记录
def WHSave(request):
    data = {
        "status": 0,
        "message": u"更新失败",
        "data": []
    }
    userid = str(request.COOKIES['userid'])
    try:
        alist = []
        taskid = request.POST['txtTaskId']
        code = Common.GenDocNum("t_dc_task", "1")  # 生成编号
        weather = request.POST['txtWeather']
        temperature = request.POST['txtTemperature']
        # weather=str(request.COOKIES['weather'])
        # temperature=int(request.COOKIES["temperature"])
        checkitem = request.POST['txtCheckItem']
        disease = request.POST['txtDiseaseId']
        remark = request.POST['txtRemark']
        urgencylevel = request.POST['txtUrgencylevel']
        piledirection = request.POST['txtPileD']
        pilekm = request.POST['txtPileKM']
        pilem = request.POST['txtPileM']
        fileids = request.POST['txtFileId']

        row = MySQLDB.CommitMySql(
            "INSERT INTO t_dc_task_disease (task_id,code,weather,temperature,urgency_level,param_partol_id,disease_id,disease_name,pile_direction,pile_km,pile_m,remark,create_user,param_process_code) select %s,'%s','%s','%s',%s,%s,disease_id,disease_name,'%s',%s,%s,'%s','%s','131' from t_sys_disease where disease_id = %s;" % (
                taskid, code, weather, temperature, urgencylevel, checkitem, piledirection, pilekm, pilem, remark,
                userid,
                disease));

        # 获取ID
        row = MySQLDB.SelectMySql(
            "SELECT task_disease_id FROM t_dc_task_disease WHERE task_id = %s and code = '%s';" % (taskid, code))
        IDnum = row[0][0]

        # 存储病害-文件关联信息
        if len(fileids) > 0:
            updataSql = ""
            temp = fileids.split('|')
            for t in temp:
                if len(t) > 0:
                    # updataSql.join("UPDATE `t_dc_task_disease_file` SET `task_disease_id` = %s WHERE `task_disease_file_id` = %s;"% (IDnum,t))
                    MySQLDB.CommitMySql(
                        "UPDATE `t_dc_task_disease_file` SET `task_disease_id` = %s WHERE `task_disease_file_id` = %s;" % (
                            IDnum, t))

        data = {
            "status": 1,
            "message": u"更新成功",
            "data": []
        }

    except Exception as e:
        return HttpResponse(e)
    return JsonResponse(data)


# 维护组处理完成任务
# 输入参数：request,taskid
# 返回参数：response
@csrf_exempt
def writeDCLWH(request):
    # md5 = request.COOKIES['loginmd5']
    # md5row = MySQLDB.SelectMySql("SELECT * FROM t_sys_user WHERE description='%s';" % md5)
    # try:
    #     if len(md5row)>0:
    #         pass
    #     else:
    #         data = {
    #         "status":3,
    #         "message":u"请重新登！",
    #         "data":[]
    #         }
    # except:
    #     data = {
    #         "status":3,
    #         "message":u"请重新登陆！",
    #         "data":[]
    #         }
    taskid = request.GET['taskid']
    # assignid = request.GET['assignid']
    userid = request.COOKIES['userid']
    user = int(userid)
    try:
        row = MySQLDB.SelectMySql(
            "SELECT  `assign_id`, `task_id`, `category`, `type`, `content`, `assign_user`, `assign_date`, `receive_user`, `receive_dept`, `receive_role_code`, `receive_date`, `complate_date`, `status`, `operation_process`, `from_id`, `from_type`, `task_disease_id` FROM `t_dc_assign` WHERE task_id='%s' ;" % taskid)  # 查询该任务安排表具体信息
        # 校验是否已经提交过该任务
        if row[0][12] == 3:
            data = {
                "status": 2,
                "message": u"该任务已提交过！",
                "data": []
            }
        else:
            locatime = time.strftime("%Y-%m-%d %X", time.localtime())
            MySQLDB.CommitMySql(
                "UPDATE `t_dc_assign` SET status=3,complate_date='%s',param_process_code = '132' WHERE task_id='%s';" % (
                    locatime, taskid))  # 改变任务安排表状态
            MySQLDB.CommitMySql(
                "UPDATE `t_dc_task` SET status=2,update_user='%s' ,update_date='%s' WHERE task_id='%s';" % (
                    user, locatime, taskid))  # 改变任务表状态

            row1 = MySQLDB.SelectMySql(
                "SELECT  `assign_id`, `task_id`, `category`, `type`, `content`, `assign_user`, `assign_date`, `receive_user`, `receive_dept`, `receive_role_code`, `receive_date`, `complate_date`, `status`, `operation_process`, `from_id`, `from_type`, `task_disease_id` FROM `t_dc_assign` WHERE task_id='%s' ;" % taskid)  # 查询该任务安排表具体信息，后面用到

            MySQLDB.CommitMySql(
                "INSERT INTO `t_dc_assign` (`category`, `type`, `content`, `assign_user`, `assign_date`, `receive_role_code`,  `status`, `from_id`, `from_type`,`task_disease_id`) VALUES (1,4,'%s','%s','%s','%s','%s','%s','%s','%s');" % (
                    row1[0][4], user, locatime, 'technology', 1, row1[0][0], 1, row1[0][16]))  # 生成通知任务安排

            data = {
                "status": 1,
                "message": u"任务提交成功",
                "data": []
            }

    except Exception as e:
        data = {
            "status": 0,
            "message": str(e),
            "data": []
        }
    jsonstr = json.dumps(data)
    return HttpResponse(jsonstr, content_type="application/json")


# 查看病害详情
def BHXQ(request, assignid):
    # md5 = request.COOKIES['loginmd5']
    # md5row = MySQLDB.SelectMySql("SELECT * FROM t_sys_user WHERE description='%s';" % md5)
    # try:
    #     if len(md5row)>0:
    #         pass
    #     else:
    #         response = render_to_response('login.html', {})
    #         return response
    # except:
    #     response = render_to_response('login.html', {})
    #     return response
    # b = request.COOKIES['powerid']
    # date = []
    # date = PowerID.PowerID(int(b))
    # DCLpower = 0
    # if date[0] == 1 or date[1] == 1 or date[2] == 1:
    #     DCLpower = 1
    diseaseinfo = DiseaseInfoByJSZ(assignid)
    diseaseid = int(diseaseinfo[0]["taskdisease_id"])
    filelist = DiseaseFileList(diseaseid)
    return render(request, 'QLGL/XJYW/RCJC_JS_DETAIL.html',
                  {'diseaseinfo': json.dumps(diseaseinfo), 'filelist': json.dumps(filelist)})
    # return response
    # return JsonResponse({'diseaseinfo':filelist})


# 功能:获取病害详情
# 输入参数:分配id
# 返回参数:数组
def DiseaseInfoByJSZ(assignid):
    alist = []
    try:
        row = MySQLDB.SelectMySql(
            "select case a.urgency_level when 1 then '另处' when 2 then '一般' when 3 then '紧急' end as urgency,c.param_name,a.disease_name,a.pile_direction,a.pile_km,a.pile_m,c.param_id,a.disease_id,urgency_level,remark,a.weather,a.temperature,a.task_disease_id from t_dc_task_disease a left join t_dc_assign b on a.task_disease_id = b.task_disease_id left join t_sys_param c on a.param_partol_id = c.param_id where b.assign_id = %s;" % assignid)

        if len(row) > 0:
            for i in range(len(row)):
                info = {}
                info["urgency"] = row[i][0]
                info["checkItem"] = row[i][1]
                info["disease_name"] = row[i][2]
                info["pile_direction"] = row[i][3]
                info["pile_km"] = row[i][4]
                info["pile_m"] = row[i][5]
                info["param_id"] = row[i][6]
                info["disease_id"] = row[i][7]
                info["urgency_level"] = row[i][8]
                info["remark"] = row[i][9]
                info["weather"] = row[i][10]
                info["temperature"] = row[i][11]
                info["taskdisease_id"] = row[i][12]
                alist.append(info)
                # alist.append({})
    except Exception as e:
        return HttpResponse(e)
    return alist


# 功能:获取病害图像列表
# 输入参数:病害id
# 返回参数:数组
def DiseaseFileList(diseaseid):
    alist = []
    try:
        row = MySQLDB.SelectMySql(
            "select task_disease_file_id,name,url,type from t_dc_task_disease_file a where task_disease_id = %s and status =1 ;" % diseaseid)

        if len(row) > 0:
            for i in range(len(row)):
                info = {}
                info["fileid"] = str(row[i][0])
                info["name"] = str(row[i][1])
                info["url"] = str(row[i][2])
                alist.append(info)
    except Exception as e:
        return HttpResponse(e)
    return alist


# 功能:获取病害历史记录
# 输入参数:分配id
# 返回参数:HttpResponse
def RW_GZ(request):
    # md5 = request.COOKIES['loginmd5']
    # md5row = MySQLDB.SelectMySql("SELECT * FROM t_sys_user WHERE description='%s';" % md5)
    # try:
    #     if len(md5row)>0:
    #         pass
    #     else:
    #         response = render_to_response('login.html', {})
    #         return response
    # except:
    #     response = render_to_response('login.html', {})
    #     return response
    # b = request.COOKIES['powerid']
    # date = []
    # date = PowerID.PowerID(int(b))
    # DCLpower = 0
    # if date[0] == 1 or date[1] == 1 or date[2] == 1:
    #     DCLpower = 1
    assignid = request.GET['assign_id']
    # 获取assign.task_disease_id
    # 获取ID
    row = MySQLDB.SelectMySql("SELECT task_disease_id FROM t_dc_assign WHERE assign_id = %s;" % (assignid))
    if len(row):
        diseaseid = row[0][0]
        historyList = HistoryInfo(diseaseid)

    # return JsonResponse({"dd":historyList})
    return render(request, 'QLGL/XJYW/RCJC_JS_HISTORY.html', {"historyList": historyList})
    # return response


def HistoryInfo(diseaseid):
    alist = []
    try:
        row = MySQLDB.SelectMySql("call diseaseHistory(%s);" % diseaseid)
        if len(row) > 0:
            for i in range(len(row)):
                if row[i][8] == 1:
                    info = {}
                    info["id"] = row[i][0]
                    info["user_id"] = row[i][1]
                    info["user_name"] = row[i][2]
                    info["task_date"] = row[i][3]
                    info["remark"] = row[i][4]
                    info["urls"] = UrlSplit(row[i][5])
                    info["status"] = row[i][6]
                    info["status_name"] = row[i][7]
                    info["type"] = row[i][8]

                    alist.append(info)
    except Exception as e:
        return HttpResponse(e)
    return alist


def UrlSplit(url):
    alist = []
    if url.find(",") == -1:
        if len(url) > 0:
            alist.append({"url": url})
    else:
        for i in url.split(","):
            info = {}
            info["url"] = i
            alist.append(info)
    return alist


# 功能:获取病害历史记录
# 输入参数:分配id
# 返回参数:HttpResponse
def RW_WH(request):
    # md5 = request.COOKIES['loginmd5']
    # md5row = MySQLDB.SelectMySql("SELECT * FROM t_sys_user WHERE description='%s';" % md5)
    # try:
    #     if len(md5row)>0:
    #         pass
    #     else:
    #         response = render_to_response('login.html', {})
    #         return response
    # except:
    #     response = render_to_response('login.html', {})
    #     return response
    # b = request.COOKIES['powerid']
    # date = []
    # date = PowerID.PowerID(int(b))
    # DCLpower = 0
    # if date[0] == 1 or date[1] == 1 or date[2] == 1:
    #     DCLpower = 1
    assignid = request.GET['assign_id']
    # 获取assign.task_disease_id
    # 获取ID
    row = MySQLDB.SelectMySql("SELECT task_disease_id FROM t_dc_assign WHERE assign_id = %s;" % (assignid))
    if len(row):
        diseaseid = row[0][0]
        historyList = HistoryInfo(diseaseid)

    # return JsonResponse({"dd":historyList})
    return render(request, 'QLGL/XJYW/RCJC_JS_HISTORY.html', {"historyList": historyList})
    # return response


# 技术组处理完成任务
# 输入参数：request,taskid，type(1:已阅知；2：不处理；3：跟踪；4：维护；5：维修)
# 返回参数：response
@csrf_exempt
def writeDCLJS(request):
    # md5 = request.COOKIES['loginmd5']
    # md5row = MySQLDB.SelectMySql("SELECT * FROM t_sys_user WHERE description='%s';" % md5)
    # try:
    #     if len(md5row)>0:
    #         pass
    #     else:
    #         data = {
    #         "status":3,
    #         "message":u"请重新登陆！",
    #         "data":[]
    #         }
    # except:
    #     data = {
    #         "status":3,
    #         "message":u"请重新登陆！",
    #         "data":[]
    #         }
    try:
        assign_id = request.GET['assign_id']
        type_k = request.GET['type']
        # assignid = request.GET['assignid']
        locatime = time.strftime("%Y-%m-%d %X", time.localtime())
        userid = request.COOKIES['userid']
        user = int(userid)

        row = MySQLDB.SelectMySql(
            "SELECT  `assign_id`, `task_id`, `category`, `type`, `content`, `assign_user`, `assign_date`, `receive_user`, `receive_dept`, `receive_role_code`, `receive_date`, `complate_date`, `status`, `operation_process`, `from_id`, `from_type`, `task_disease_id` FROM `t_dc_assign` WHERE assign_id='%s' ;" % assign_id)  # 查询该任务安排表具体信息

        # 校验是否已经提交过该任务
        if row[0][12] == 3:
            data = {
                "status": 2,
                "message": u"该任务已提交过！",
                "data": []
            }
        else:
            if type_k == "1":
                MySQLDB.CommitMySql(
                    "UPDATE `t_dc_assign` SET status=3,complate_date='%s',operation_process='%s',param_process_code = case type when 1 then '113' when 4 then '133' end WHERE assign_id='%s';" % (
                        locatime, type_k, assign_id))  # 改变任务安排表状态
            elif type_k == "2":
                MySQLDB.CommitMySql(
                    "UPDATE `t_dc_assign` SET status=3,complate_date='%s',operation_process='%s',param_process_code=141 WHERE assign_id='%s';" % (
                        locatime, type_k, assign_id))  # 改变任务安排表状态
            elif type_k == "3":
                MySQLDB.CommitMySql(
                    "UPDATE `t_dc_assign` SET status=3,complate_date='%s',operation_process='%s',param_process_code = case type when 2 then '114' when 3 then '123' end  WHERE assign_id='%s';" % (
                        locatime, type_k, assign_id))  # 改变任务安排表状态
                row1 = MySQLDB.SelectMySql(
                    "SELECT  `assign_id`, `task_id`, `category`, `type`, `content`, `assign_user`, `assign_date`, `receive_user`, `receive_dept`, `receive_role_code`, `receive_date`, `complate_date`, `status`, `operation_process`, `from_id`, `from_type`, `task_disease_id` FROM `t_dc_assign` WHERE assign_id='%s' ;" % assign_id)  # 任务内容查询

                now = datetime.datetime.now()
                date = now + datetime.timedelta(days=1)
                MySQLDB.CommitMySql(
                    "INSERT INTO `t_dc_task`(`content`, `task_date`, `type`, `status`,  `create_user`, `create_date`) VALUES ('%s','%s','%s','%s','%s','%s');" % (
                        row1[0][4], date, 2, 1, user, locatime))  # 生成任务表
                row2 = MySQLDB.SelectMySql(
                    "SELECT `task_id`, `content`, `task_date`, `type`, `status`, `weather`, `temperature`, `create_user`, `create_date`, `update_user`, `update_date` FROM `t_dc_task`  WHERE content='%s' and create_user='%s' and  create_date='%s' ;" % (
                        row1[0][4], user, locatime))  # 查询task_id

                MySQLDB.CommitMySql(
                    "INSERT INTO `t_dc_assign` (`task_id`,`category`, `type`, `content`, `assign_user`, `assign_date`, `receive_role_code`,  `status`, `from_id`, `from_type`, `task_disease_id`,`param_process_code`) VALUES ('%s',2,3,'%s','%s','%s','%s','%s','%s','%s','%s','122');" % (
                        row2[0][0], row1[0][4], user, locatime, 'inspection', 1, row1[0][0], 1, row1[0][16]))  # 生成任务安排

            elif type_k == "4":
                MySQLDB.CommitMySql(
                    "UPDATE `t_dc_assign` SET status=3,complate_date='%s',operation_process='%s',param_process_code = '115' WHERE assign_id='%s';" % (
                        locatime, type_k, assign_id))  # 改变任务安排表状态
                row1 = MySQLDB.SelectMySql(
                    "SELECT  `assign_id`, `task_id`, `category`, `type`, `content`, `assign_user`, `assign_date`, `receive_user`, `receive_dept`, `receive_role_code`, `receive_date`, `complate_date`, `status`, `operation_process`, `from_id`, `from_type`, `task_disease_id` FROM `t_dc_assign` WHERE assign_id='%s' ;" % assign_id)  # 任务内容查询
                MySQLDB.CommitMySql(
                    "INSERT INTO `t_dc_task`(`content`, `task_date`, `type`, `status`,  `create_user`, `create_date`) VALUES ('%s','%s','%s','%s','%s','%s');" % (
                        row1[0][4], locatime, 3, 1, user, locatime))  # 生成任务表
                row2 = MySQLDB.SelectMySql(
                    "SELECT `task_id`, `content`, `task_date`, `type`, `status`, `weather`, `temperature`, `create_user`, `create_date`, `update_user`, `update_date` FROM `t_dc_task`  WHERE content='%s' and create_user='%s' and  create_date='%s' ;" % (
                        row1[0][4], user, locatime))  # 查询task_id

                MySQLDB.CommitMySql(
                    "INSERT INTO `t_dc_assign` (`task_id`,`category`, `type`, `content`, `assign_user`, `assign_date`, `receive_role_code`,  `status`, `from_id`, `from_type`, `task_disease_id`,`param_process_code`) VALUES ('%s',2,4,'%s','%s','%s','%s','%s','%s','%s','%s','131');" % (
                        row2[0][0], row1[0][4], user, locatime, 'maintenance', 1, row1[0][0], 1,
                        row1[0][16]))  # 生成通知任务安排

            elif type_k == "5":
                MySQLDB.CommitMySql(
                    "UPDATE `t_dc_assign` SET status=3,complate_date='%s',operation_process='%s',param_process_code = '151' WHERE assign_id='%s';" % (
                        locatime, type_k, assign_id))  # 改变任务安排表状态
            else:
                pass

            data = {
                "status": 1,
                "message": u"任务提交成功",
                "data": []
            }

    except Exception as e:
        data = {
            "status": 0,
            "message": str(e),
            "data": []
        }
    jsonstr = json.dumps(data)
    return HttpResponse(jsonstr, content_type="application/json")


# 病害库
@auth
def QLXJ_XJYW_BHK_index(request):
    return render(request, 'QLGL/XJYW/BHK.html')


# 病害库数据
@authjson
def QLXJ_XJYW_BHK_DATA(request):
    alist = []
    try:
        row = MySQLDB.SelectMySql(
            "select b.task_disease_id,b.code,c.param_name,b.disease_name,CONCAT(b.pile_direction,':K',b.pile_km,'+',b.pile_m) as pile,b.create_date,(select param_name from t_sys_param where param_code = a.param_process_code) as status,ifnull(d.bridge_name,'') from t_dc_assign a inner join t_dc_task_disease b on a.task_disease_id = b.task_disease_id left join t_sys_param c on b.param_partol_id = c.param_id left join t_bridge_base d on b.bridge_id = d.bridge_id where a.type = 2 and a.category = 2;")
        if len(row) > 0:
            for i in range(len(row)):
                info = {}
                info["bhkcode"] = str(row[i][1])
                info["bhkparam"] = str(row[i][2])
                info["bhkdises"] = str(row[i][3])
                info["bhkpile"] = str(row[i][4])
                a = str(row[i][5])
                tmp = a.split(' ', 1)
                info["bhktime"] = tmp[0]
                info["JCtaskid"] = row[i][0]
                info["bhkstatus"] = row[i][6]
                info["bridge_name"] = row[i][7]
                alist.append(info)
        else:
            alist = []

        data = {
            "status": 1,
            "message": u"查询成功",
            "data": alist
        }
    except Exception as e:
        data = {
            "status": 0,
            "message": e.message,
            "data": []
        }
    return JsonResponse(data)


@auth
def QLXJ_XJYW_BHK_XQ(request):
    diseaseid = request.GET['diseaseid']
    a = int(diseaseid)
    historyList = HistoryInfoXQ(a)
    return render(request, 'QLGL/XJYW/BHK_HISTORY.html', {"historyList": historyList})


def HistoryInfoXQ(diseaseid):
    alist = []
    try:
        row = MySQLDB.SelectMySql("call diseaseHistory(%s);" % diseaseid)
        if len(row) > 0:
            for i in range(len(row)):
                if row[i][8] == 1:
                    info = {}
                    info["id"] = row[i][0]
                    info["user_id"] = row[i][1]
                    info["user_name"] = row[i][2]
                    info["task_date"] = row[i][3]
                    info["remark"] = row[i][4]
                    info["urls"] = UrlSplit(row[i][5])
                    info["status"] = row[i][6]
                    info["status_name"] = row[i][7]
                    info["type"] = row[i][8]

                    alist.append(info)
    except Exception as e:
        return HttpResponse(e)
    return alist


@auth
def QLXJ_XJYW_WHJL_index(request):
    return render(request, 'QLGL/XJYW/WHJL.html')


@authjson
def QLXJ_XJYW_WHJL_DATA(request):
    try:
        row = MySQLDB.SelectMySql(
            "select b.task_disease_id,b.code,a.complate_date,c.real_name,ifnull(d.param_name,'') ,b.disease_name,CONCAT(b.pile_direction,':K',b.pile_km,'+',b.pile_m) as pile,b.remark from t_dc_assign a inner join t_dc_task_disease b on a.task_id = b.task_id left join t_sys_user c on b.create_user = c.user_id left join t_sys_param d on b.param_partol_id = d.param_id where a.type = 4 and a.status = 3 and a.category = 2 order by b.create_date desc")
        # 字典数据
        alist = []
        if len(row) > 0:
            for i in range(len(row)):
                info = {}
                info["bhkcode"] = str(row[i][1])
                a = str(row[i][2])
                tmp = a.split(' ', 1)
                info["bhktime"] = tmp[0]
                info["bhkname"] = str(row[i][3])
                info["bhkparam"] = str(row[i][4])
                info["bhkdises"] = str(row[i][5])
                info["bhkpile"] = str(row[i][6])
                info["bhkremak"] = str(row[i][7])
                info["JCtaskid"] = row[i][0]
                # 获取图片url
                urlrow = MySQLDB.SelectMySql(
                    "select task_disease_file_id, name, url from t_dc_task_disease_file where task_disease_id = %s and status = 1 order by task_disease_file_id desc" %
                    row[i][0])
                try:
                    info["picURL"] = urlrow[0][2]
                except:
                    info["picURL"] = "/static/img/error.png"
                alist.append(info)

        data = {
            "status": 1,
            "message": u"查询成功",
            "data": alist
        }
    except Exception as e:
        data = {
            "status": 0,
            "message": e.message,
            "data": []
        }
    return JsonResponse(data)


@auth
def QLXJ_XJYW_RCJCN(request):
    return render(request, "QLGL/XJYW/RCJCN.html", {})


# 日常巡检数据
@authjson
def QLXJ_XJYW_RCXJ_DATA(request):
    try:
        row = Common.ConverToDICT(MySQLDB.SelectMySql(
            "select b.task_id,d.name,ifnull(b.weather,'') weather,ifnull(b.temperature,'') temperature,b.update_user,c.real_name,date_format(b.task_date,'%Y-%m-%d %T'),(select count(1) from t_dc_task_disease h where task_id = b.task_id and status=1) diseaseCount,b.status from t_dc_assign a inner join t_dc_task b on a.task_id = b.task_id left join t_sys_user c on b.charge_user = c.user_id left join t_sys_organize d on b.charge_dept = d.organize_id where a.category = 2 and a.type = 1 and b.status != 3;"),
            ["taskid", "rolename", "weather", "temperature", "userid", "username", "checkdate",
             "diseaseCount", "status"])
        data = dict(status=1, message="查询成功", data=row)
    except Exception as e:
        data = dict(status=0, message="查询失败", data=[])
    return JsonResponse(data)


@auth
def QLXJ_XJYW_RCXJ_SEE(request):
    task_id = request.GET.get("task_id", 0)
    return render(request, "QLGL/XJYW/RCJCN_SEE.html", {"task_id": json.dumps(task_id)})


# 日常巡检任务记录数据
@authjson
def QLXJ_XJYW_RCXJ_RECORD_DATA(request):
    task_id = request.GET.get("task_id", 0)
    try:
        row = Common.ConverToDICT(MySQLDB.SelectMySql(
            "select task_disease_id,code,case urgency_level when 1 then '另处' when 2 then '一般' when 3 then '紧急' end urgency,(select param_name from t_sys_param where param_id =a.param_partol_id) partol,disease_id,disease_name,CONCAT(a.pile_direction,a.pile_km,'+',a.pile_m) pile,date_format(a.create_date,'%%Y-%%m-%%d %%T') check_date,a.remark,b.bridge_name from t_dc_task_disease a left join t_bridge_base b on a.bridge_id = b.bridge_id where task_id = %s and a.status=1;" % task_id),
            ["task_disease_id", "code", "urgency", "partol", "disease_id", "disease_name", "pile", "check_date",
             "remark", "bridge_name"])
        data = dict(status=1, message="查询成功", data=row)
    except Exception as e:
        data = dict(status=0, message="查询失败", data=[])
    return JsonResponse(data)


def QLXJ_XJYW_RCXJ_RECORD_ADD(request):
    taskid = request.GET.get('task_id', 0)
    dailycheckitems = selDCItems()
    weatherinfo = {}
    # 判断是否已经有天气记录
    tasktq = taskWeather(taskid)
    bridgeinfo = []
    try:
        row = MySQLDB.SelectMySql(
                "SELECT bridge_id,bridge_name from t_bridge_base where status=1;")
        if len(row) > 0:
            key = ["bridge_id", "bridge_name"]
            for i in range(len(row)):
                info = {}
                for j in range(len(key)):
                    info[key[j]] = row[i][j]
                bridgeinfo.append(info)
    except Exception as e:
        pass
    if int(tasktq[0]['hasData']) > 0:
        weatherinfo = dict(weather=tasktq[0]['weather'], temperature=tasktq[0]['temperature'])
    return render(request, 'QLGL/XJYW/RCJCN_SEE_ADD.html',
                  {'taskid': taskid, 'dcitems': dailycheckitems, "weatherinfo": weatherinfo, "bridgeinfo":bridgeinfo})


def QLXJ_XJYW_RCXJ_RECORD_ADDSAVE(request):
    userid = str(request.COOKIES['userid'])
    try:
        taskid = request.POST['txtTaskId']
        code = Common.GenDocNum("t_dc_task", "1")  # 生成编号
        weather = request.POST['txtWeather']
        temperature = request.POST['txtTemperature']
        checkitem = request.POST['txtCheckItem']
        disease = request.POST['txtDiseaseId']
        remark = request.POST['txtRemark']
        urgencylevel = request.POST['txtUrgencylevel']
        piledirection = request.POST['txtPileD']
        pilekm = request.POST['txtPileKM']
        pilem = request.POST['txtPileM']
        bridgeid = request.POST.get("bridge_id",0)
        fileids = request.POST['txtFileId']

        row = MySQLDB.CommitMySql(
            "INSERT INTO t_dc_task_disease (task_id,code,weather,temperature,urgency_level,param_partol_id,disease_id,disease_name,pile_direction,pile_km,pile_m,remark,create_user,param_process_code, bridge_id) select %s,'%s','%s','%s',%s,%s,disease_id,disease_name,'%s',%s,%s,'%s','%s','111','%s' from t_sys_disease where disease_id = %s;" % (
                taskid, code, weather, temperature, urgencylevel, checkitem, piledirection, pilekm, pilem, remark,
                userid,bridgeid,disease))

        # 获取ID
        row = MySQLDB.SelectMySql(
            "SELECT task_disease_id FROM t_dc_task_disease WHERE task_id = %s and code = '%s';" % (taskid, code))
        IDnum = row[0][0]

        # 存储病害-文件关联信息
        if len(fileids) > 0:
            updataSql = ""
            temp = fileids.split('|')
            for t in temp:
                if len(t) > 0:
                    MySQLDB.CommitMySql(
                        "UPDATE `t_dc_task_disease_file` SET `task_disease_id` = %s WHERE `task_disease_file_id` = %s;" % (
                            IDnum, t))

        data = dict(status=1, message=u"更新成功", data=[])

    except Exception as e:
        data = dict(status=0, message=u"更新失败", data=[])
    return JsonResponse(data)


def QLXJ_XJYW_RCXJ_RECORD_MODIFY(request):
    taskid = request.GET.get('task_id', 0)
    task_disease_id = request.GET.get('task_disease_id', 0)
    dailycheckitems = selDCItems()
    taskdiseaseinfo = Common.ConverToDICT(Common.GetTaskDiseaseById(task_disease_id),
                                          ["task_disease_id", "task_id", "code", "weather", "temperature",
                                           "urgency_level", "param_partol_id", "disease_id", "disease_name",
                                           "pile_direction", "pile_km", "pile_m", "remark", "bridge_name"])
    checkitemdisease = Common.ConverToDICT(Common.GetDiseaseByCheckItem(taskdiseaseinfo[0]["param_partol_id"]),
                                           ["disease_id", "disease_name"])
    diseasefiles = Common.ConverToDICT(Common.GetDiseaseFileById(task_disease_id),
                                       ["task_disease_file_id", "task_disease_id", "name", "url", "type", "description",
                                        "create_user", "create_date", "update_user", "update_date"])
    txtFileId = ''
    for i in range(len(diseasefiles)):
        if i == 0:

            txtFileId = txtFileId + str(diseasefiles[i]["task_disease_file_id"])
        else:
            txtFileId = txtFileId + "|" + str(diseasefiles[i]["task_disease_file_id"])

    return render(request, 'QLGL/XJYW/RCJCN_SEE_MODIFY.html',
                  {'taskid': taskid, 'dcitems': dailycheckitems, "checkitemdisease": checkitemdisease,
                   "taskdiseaseinfo": taskdiseaseinfo, "diseasefiles": diseasefiles, "txtFileId": txtFileId})


def QLXJ_XJYW_RCXJ_RECORD_MODIFYSAVE(request):
    userid = str(request.COOKIES['userid'])
    try:
        taskdiseaseid = request.POST['txtTaskDiseaseId']
        weather = request.POST['txtWeather']
        temperature = request.POST['txtTemperature']
        checkitem = request.POST['txtCheckItem']
        disease = request.POST['txtDiseaseId']
        diseasename = request.POST['txtDiseaseName']
        remark = request.POST['txtRemark']
        urgencylevel = request.POST['txtUrgencylevel']
        piledirection = request.POST['txtPileD']
        pilekm = request.POST['txtPileKM']
        pilem = request.POST['txtPileM']
        fileids = str(request.POST['txtFileId'])

        updatasql = "UPDATE `t_dc_task_disease` SET `weather` = '%s',`temperature` = %s,`urgency_level` = %s,`param_partol_id` = %s,`disease_id` = %s,`disease_name` = '%s',`pile_direction` = '%s',`pile_km` = %s,`pile_m` = %s,`remark` = '%s', update_user = '%s', update_date = now() WHERE `task_disease_id` = %s;" % (
            weather, temperature, urgencylevel, checkitem, disease, diseasename, piledirection, pilekm, pilem, remark,
            userid,
            taskdiseaseid)
        row = MySQLDB.CommitMySql(updatasql)
        if row != 'ok':
            raise Exception(row)

        # 存储病害-文件关联信息
        if len(fileids) > 0:
            temp = fileids.split('|')
            # 取得原有数据信息
            diseasefiles = Common.ConverToDICT(Common.GetDiseaseFileById(taskdiseaseid),
                                               ["task_disease_file_id", "task_disease_id", "name", "url", "type",
                                                "description",
                                                "create_user", "create_date", "update_user", "update_date"])
            originalFileIds = [str(w["task_disease_file_id"]) for w in diseasefiles]
            # 两种情况，1、原来有，现在无，删除；2、原来无，现在有，增加
            # for i in originalFileIds:
            #     if i not in temp:
            #         MySQLDB.CommitMySql(
            #             "UPDATE `t_dc_task_disease_file` SET `task_disease_id` = %s WHERE `task_disease_file_id` = %s;" % (
            #                 taskdiseaseid, i))
            # for i in temp:
            #     if i not in originalFileIds:
            #         deletesql = "update t_dc_task_disease_file set status = 0 where task_disease_file_id = %s;" % i[
            #             "task_disease_file_id"]
            #         row = MySQLDB.CommitMySql(deletesql)
            #         if row != 'ok':
            #             raise Exception(row)
            for i in [w for w in diseasefiles if w["task_disease_file_id"] not in temp]:
                deletesql = "update t_dc_task_disease_file set status = 0 where task_disease_file_id = %s;" % i[
                    "task_disease_file_id"]
                row = MySQLDB.CommitMySql(deletesql)
                if row != 'ok':
                    raise Exception(row)
            for t in [w for w in temp if w not in originalFileIds]:
                if len(t) > 0:
                    MySQLDB.CommitMySql(
                        "UPDATE `t_dc_task_disease_file` SET `task_disease_id` = %s,status = 1 WHERE `task_disease_file_id` = %s;" % (
                            taskdiseaseid, t))
        else:
            # 删除所有病害文件
            deletesql = "update t_dc_task_disease_file set status = 0 where task_disease_id = %s;" % taskdiseaseid
            row = MySQLDB.CommitMySql(deletesql)
            if row != 'ok':
                raise Exception(row)
        data = dict(status=1, message=u"更新成功", data=[])

    except Exception as e:
        data = dict(status=0, message=u"更新失败", data=[])
    return JsonResponse(data)


# 日巡记录删除
def QLXJ_XJYW_RCXJ_RECORD_DELETESAVE(request):
    task_disease_id = request.GET.get('task_disease_id', 0)
    try:
        deletesql = "UPDATE t_dc_task_disease SET status = 0 WHERE task_disease_id = %s;" % task_disease_id
        MySQLDB.CommitMySql(deletesql)
        data = dict(status=1, message=u"删除成功", data=[])
    except Exception as e:
        data = dict(status=0, message=u"删除失败", data=[])
    return JsonResponse(data)


# 日巡多媒体信息
def QLXJ_XJYW_RCXJ_RECORD_MEDIA(request):
    task_disease_id = request.GET.get('task_disease_id', 0)
    try:
        diseasefiles = Common.ConverToDICT(Common.GetRCJCRecordMedia(task_disease_id),
                                           ["task_disease_file_id", "task_disease_id", "name", "url", "type",
                                            "description",
                                            "create_user", "create_date", "update_user", "update_date"])
        data = dict(status=1, message=u"更新成功", data=diseasefiles)
    except Exception as e:
        data = dict(status=0, message=u"查询失败", data=[])
    return JsonResponse(data)


def QLXJ_XJYW_RCXJ_MODIFY(request):
    task_id = request.GET.get('task_id', 0)
    taskinfo = []
    deptinfo = []
    userInfo = []
    try:
        taskinfo = Common.ConverToDICT(Common.GetRCXJTaskInfo(task_id),
                                       ["task_id", "content", "task_date", "type", "status", "weather", "temperature",
                                        "charge_dept", "charge_user"])
        row2 = MySQLDB.SelectMySql(
            "SELECT organize_id,name from t_sys_organize where status = 1 and category=2;")
        if len(row2) > 0:
            key = ["organize_id", "name"]
            for i in range(len(row2)):
                info = {}
                for j in range(len(key)):
                    info[key[j]] = row2[i][j]
                deptinfo.append(info)
        if taskinfo[0]["charge_dept"]:
            row1 = MySQLDB.SelectMySql(
                "SELECT user_id,real_name from t_sys_user where status = 1 and dept_id = '%s';" % (
                taskinfo[0]["charge_dept"]))
            if len(row1) > 0:
                key = ["user_id", "real_name"]
                for i in range(len(row1)):
                    info = {}
                    for j in range(len(key)):
                        info[key[j]] = row1[i][j]
                    userInfo.append(info)
    except Exception as e:
        pass
    return render(request, 'QLGL/XJYW/RCJCN_MODIFY.html',
                  {'taskinfo': taskinfo, 'deptinfo': deptinfo, 'userInfo': userInfo})


def QLXJ_XJYW_RCXJ_MODIFYSAVE(request):
    userid = request.COOKIES.get("userid", 0)
    task_id = request.POST.get('task_id', 0)
    weather = request.POST.get('txtWeather', '')
    temperature = request.POST.get('txtTemperature', 0)
    charge_dept = request.POST.get('charge_dept', 0)
    charge_user = request.POST.get('charge_user', 0)

    try:
        updatesql = "update t_dc_task set weather='%s',temperature='%s',update_user = '%s',charge_user='%s',charge_dept='%s',update_date = now() where task_id = %s;" % (
            weather, temperature, userid, charge_user, charge_dept, task_id)
        MySQLDB.CommitMySql(updatesql)
        data = dict(status=1, message=u"修改成功", data=[])
    except Exception as e:
        data = dict(status=0, message=u"修改失败", data=[])
    return JsonResponse(data)


def QLXJ_XJYW_RCXJ_DELETESAVE(request):
    userid = request.COOKIES.get("userid", 0)
    task_id = request.GET.get('task_id', 0)
    try:
        updatesql = "update t_dc_task set status=3,update_user = %s,update_date = now() where task_id = %s;" % (
            userid, task_id)
        MySQLDB.CommitMySql(updatesql)
        data = dict(status=1, message=u"删除成功", data=[])
    except Exception as e:
        data = dict(status=0, message=u"删除失败", data=[])
    return JsonResponse(data)


def QLXJ_XJYW_JCJC_INDEX_DATA(request):
    try:
        # todo 注意检查项目未实现
        list = Common.ConverToDICT(Common.GetJCJCList(),
                                   ["check_id", "bridge_id", "bridge_name", "bridge_code", "check_depart",
                                    "check_depart_name",
                                    "user_charge_name", "from_date", "to_date", "score", "grade", "status",
                                    "diseaseCount",
                                    "checkitems"])
        data = dict(status=1, message=u"查询成功", data=list)
    except Exception as e:
        data = dict(status=0, message=u"查询失败", data=[])
    return JsonResponse(data)


def QLXJ_XJYW_JCJC_ADD(request):
    user_id = request.COOKIES["userid"]
    bridgeInfo = []
    userInfo = []
    deptInfo = []
    organize_id = 0
    try:
        row = MySQLDB.SelectMySql(
            "SELECT bridge_id,bridge_name from t_bridge_base where status=1;")
        if len(row) > 0:
            key = ["bridge_id", "bridge_name"]
            for i in range(len(row)):
                info = {}
                for j in range(len(key)):
                    info[key[j]] = row[i][j]
                bridgeInfo.append(info)
        row3= MySQLDB.SelectMySql(
            "SELECT dept_id from t_sys_user where user_id='%s' and status=1 ;"%(user_id))
        organize_id = row3[0][0]
        # 定期检查新增单位列表
        row2 = MySQLDB.SelectMySql(
            "SELECT organize_id,name from t_sys_organize where status = 1 and category=2;")
        if len(row2) > 0:
            key = ["organize_id", "name"]
            for i in range(len(row2)):
                info = {}
                for j in range(len(key)):
                    info[key[j]] = row2[i][j]
                deptInfo.append(info)
            # 经常检查新增用户列表
            row1 = MySQLDB.SelectMySql(
                "SELECT user_id,real_name from t_sys_user where status = 1 and dept_id=%s;" % row2[0][0] )
            if len(row1) > 0:
                key = ["user_id", "real_name"]
                for i in range(len(row1)):
                    info = {}
                    for j in range(len(key)):
                        info[key[j]] = row1[i][j]
                    userInfo.append(info)

    except Exception as e:
        pass
    return render(request, 'QLGL/XJYW/JCJC_ADD.html',
                  {"user_id": int(user_id), "bridgeInfo": bridgeInfo, "userInfo": userInfo, "deptInfo": deptInfo,"organize_id":organize_id})


def QLXJ_XJYW_JCJC_ADDSAVE(request):
    bridge_id = request.POST.get('bridge_id', 0)
    user_id = request.POST.get('user_id', 0)
    real_name = request.POST.get('real_name', '')
    organize_id = request.POST.get('organize_id', 0)
    organizename = request.POST.get('organize_name', '')
    fromdate = request.POST.get('from_date', '')
    todate = request.POST.get('to_date', '')
    checkitems = request.POST.get('checkitems', '')
    createdate = time.strftime('%Y-%m-%d %X', time.localtime(time.time()))
    try:
        # 经常检查首页数据
        row = MySQLDB.CommitMySql(
            "INSERT INTO `t_check_often`(`bridge_id`,`bridge_name`,`bridge_code`,`from_date`, to_date,`check_depart`,`check_depart_name`,`user_charge`,`user_charge_name`,`status`,create_date) select bridge_id,bridge_name,bridge_code,'%s','%s','%s','%s','%s','%s',1,'%s' from t_bridge_base where bridge_id = '%s';" % (
                fromdate, todate, organize_id, organizename, user_id, real_name, createdate, bridge_id))
        # 获取插入id
        row = MySQLDB.SelectMySql(
            "select check_id from t_check_often where bridge_id = %s and create_date = '%s' and status = 1;" % (
            bridge_id, createdate))
        if len(row) != 1:
            raise Exception("数据错误")
        checkid = row[0][0]
        # 插入数据
        if checkitems.strip():
            for i in checkitems.split('|'):
                insertsql = "insert into t_check_often_items (check_id,param_bridge_type_code,parts_code,parts_sub_id,parts_sub_name)  select %s,param_bridge_type_code,parts_code,parts_sub_id,name from t_sys_parts_sub where parts_sub_id = %s;" % (
                    checkid, i)
                # print insertsql
                row = MySQLDB.CommitMySql(insertsql)
                if row != "ok":
                    raise Exception(row)
        data = {
            "status": 1,
            "message": u"新增保存成功",
            "data": []
        }
    except Exception as e:
        data = {
            "status": 0,
            "message": u"新增保存失败",
            "data": []
        }
    return JsonResponse(data)


def QLXJ_XJYW_JCJC_ADD_CHECKITEM(request):
    bridgeid = request.GET.get("bridge_id", 0)
    bridgeparts = []
    partssub = []
    try:
        row = Common.GetPartsListByBridge(bridgeid)
        if len(row) > 0:
            for i in range(len(row)):
                bridgeparts.append(dict(partsid=row[i][5], partsname=row[i][2]))
                # partssub = Common.ConverToDICT(Common.GetPartsSub(bridgetype, partscode))
        data = dict(status=1, message=u"查询成功", data={"partsList": bridgeparts, "partsSub": partssub})
    except Exception as e:
        data = dict(status=0, message=u"查询失败", data=[])
    return JsonResponse(data)


# 查询部件下子部件数据
def QLXJ_XJYW_JCJC_ADD_CHECKITEM_SUB(request):
    partsid = request.GET.get("parts_id", 0)
    try:
        selectsql = "select param_bridge_type_code,parts_code from t_sys_bridge_parts where bridge_parts_id = %s;" % partsid
        row = MySQLDB.SelectMySql(selectsql)
        if len(row) > 0:
            a = Common.GetPartsSub(row[0][0], row[0][1])
            partssub = Common.ConverToDICT(a, ["parts_sub_id", "param_bridge_type_code", "parts_code", "position_code",
                                               "name"])
        data = dict(status=1, message=u"查询成功", data=partssub)
    except Exception as e:
        data = dict(status=0, message=u"查询失败", data=[])
    return JsonResponse(data)


def QLXJ_XJYW_JCJC_MODIFY(request):
    user_id = request.COOKIES["userid"]
    check_id = request.GET.get("check_id", 0)
    bridgeInfo = []
    userInfo = []
    deptInfo = []
    taskinfo = []
    try:
        row = MySQLDB.SelectMySql(
            "SELECT bridge_id,bridge_name from t_bridge_base where status=1;")
        if len(row) > 0:
            key = ["bridge_id", "bridge_name"]
            for i in range(len(row)):
                info = {}
                for j in range(len(key)):
                    info[key[j]] = row[i][j]
                bridgeInfo.append(info)
        # 经常检查新增单位列表
        row2 = MySQLDB.SelectMySql(
            "SELECT organize_id,name from t_sys_organize where status = 1 and category = 2;")
        if len(row2) > 0:
            key = ["organize_id", "name"]
            for i in range(len(row2)):
                info = {}
                for j in range(len(key)):
                    info[key[j]] = row2[i][j]
                deptInfo.append(info)
            # 经常检查新增用户列表
            row1 = MySQLDB.SelectMySql(
                "SELECT user_id,real_name from t_sys_user where status = 1 and dept_id=%s;" % row2[0][0] )
            if len(row1) > 0:
                key = ["user_id", "real_name"]
                for i in range(len(row1)):
                    info = {}
                    for j in range(len(key)):
                        info[key[j]] = row1[i][j]
                    userInfo.append(info)
        # 经常检查数据
        taskinfo = Common.ConverToDICT(Common.GetJCJCData(check_id),
                                       ["check_id", "bridge_id", "bridge_name", "bridge_code", "check_depart",
                                        "check_depart_name",
                                        "user_charge_name", "from_date", "to_date", "score", "grade", "status"])
        parts = Common.ConverToDICT(Common.GetJCJCPartSub(check_id),
                                    ["check_item_id", "check_id", "parts_code", "parts_sub_id", "parts_sub_name",
                                     "status", "bridge_parts_id"])
    except Exception as e:
        pass
    return render(request, 'QLGL/XJYW/JCJC_MODIFY.html',
                  {"user_id": int(user_id), "bridgeInfo": bridgeInfo, "userInfo": userInfo, "deptInfo": deptInfo,
                   "taskInfo": taskinfo, "checkitems": json.dumps(parts)})


def QLXJ_XJYW_JCJC_MODIFYSAVE(request):
    check_id = request.POST.get('check_id', 0)
    bridge_id = request.POST.get('bridge_id', 0)
    bridge_name = request.POST.get('bridge_name', '')
    user_id = request.POST.get('user_id', 0)
    real_name = request.POST.get('real_name', '')
    organize_id = request.POST.get('organize_id', 0)
    organizename = request.POST.get('organize_name', '')
    fromdate = request.POST.get('from_date', '')
    todate = request.POST.get('to_date', '')
    checkitems = str(request.POST.get('checkitems', ''))
    try:
        # 经常检查首页数据
        row = MySQLDB.CommitMySql(
            "UPDATE t_check_often a,t_bridge_base b SET a.bridge_id = b.bridge_id,a.bridge_name = b.bridge_name,a.bridge_code = b.bridge_code,a.from_date= '%s',a.to_date='%s',a.check_depart= '%s',a.check_depart_name= '%s',a.user_charge= '%s',a.user_charge_name = '%s' WHERE a.check_id = '%s' and b.bridge_id ='%s';" % (
                fromdate, todate, organize_id, organizename, user_id, real_name, check_id, bridge_id))
        # 调整子部件清单，1、原来有，现在没得，删除；2、原来没得，现在有，新增
        if checkitems.strip():
            # 获取原有数据
            parts = Common.ConverToDICT(Common.GetJCJCPartSub(check_id),
                                        ["check_item_id", "check_id", "parts_code", "parts_sub_id", "parts_sub_name",
                                         "status", "bridge_parts_id"])
            ids = [str(w["parts_sub_id"]) for w in parts]
            newids = checkitems.split('|')
            # 原来有，现在没得，删除
            for i in [w for w in ids if w not in newids]:
                deletesql = "update t_check_often_items set status = 0 where check_id = '%s' and parts_sub_id = '%s'" % (
                    check_id, i)
                row = MySQLDB.CommitMySql(deletesql)
                if row != 'ok':
                    raise Exception(row)
            # 原来没，现在有，新增
            for i in [w for w in newids if w not in ids]:
                insertsql = "insert into t_check_often_items (check_id,param_bridge_type_code,parts_code,parts_sub_id,parts_sub_name)  select %s,param_bridge_type_code,parts_code,parts_sub_id,name from t_sys_parts_sub where parts_sub_id = %s;" % (
                    check_id, i)
                row = MySQLDB.CommitMySql(insertsql)
                if row != "ok":
                    raise Exception(row)
        data = {
            "status": 1,
            "message": u"修改保存成功",
            "data": []
        }
    except Exception as e:
        data = dict(status=0, message=u"修改保存失败", data=[])
    return JsonResponse(data)


def QLXJ_XJYW_JCJC_DELETESAVE(request):
    check_id = request.GET.get('check_id', 0)
    try:
        deletesql = "update t_check_often set status = 0 where check_id = '%s';" % check_id
        row = MySQLDB.CommitMySql(deletesql)
        if row != 'ok':
            raise Exception(deletesql)
        data = dict(status=1, message=u"删除成功", data=[])
    except Exception as e:
        data = dict(status=0, message=u"删除失败", data=[])
    return JsonResponse(data)


def QLXJ_XJYW_JCJC_SEE(request):
    check_id = request.GET['check_id']
    bridge_id = request.GET['bridge_id']
    return render(request, 'QLGL/XJYW/JCJC_SEE.html',
                  {"check_id": json.dumps(check_id), "bridge_id": json.dumps(bridge_id)})


def QLXJ_XJYW_JCJC_SEE_DATA(request):
    check_id = request.GET['check_id']
    datalist = []
    try:
        # 定期检查查看页面数据
        row = MySQLDB.SelectMySql(
            "SELECT a.check_record_id,a.record_code,b.parts_name,disease_name,member_name,member_no,check_date,level,position,remark,description from t_check_often_record a inner join t_sys_parts b on b.parts_code = a.parts_code where a.status = 1 and a.check_id = '%s';" % (
                check_id))
        if len(row) > 0:
            key = ["check_record_id", "record_code", "parts_name", "disease_name", "member_name", "member_no",
                   "check_date", "level", "position", "remark", "description"]
            for i in range(len(row)):
                info = {}
                for j in range(len(key)):
                    info[key[j]] = row[i][j]
                datalist.append(info)
        data = dict(status=1, message=u"删除成功", data=datalist)
    except Exception as e:
        data = dict(status=0, message=u"删除失败", data=[])
    return JsonResponse(data)


def QLXJ_XJYW_JCJC_DISEASE_ADD(request):
    check_id = request.GET['check_id']
    bridge_id = request.GET['bridge_id']
    PartsInfo = []
    try:
        row = Common.GetPartsListByBridge(bridge_id)
        # 数据过滤，设置检查部件后，选择的部件才可以选择
        parts = Common.ConverToDICT(Common.GetJCJCPartSub(check_id),
                                    ["check_item_id", "check_id", "parts_code", "parts_sub_id", "parts_sub_name",
                                     "status", "bridge_parts_id"])
        partscodes = [w["parts_code"] for w in parts]
        if len(row) > 0:
            key = ["parts_no", "parts_code", "bridge_parts_name", "position_code", "param_bridge_type_code",
                   "bridge_parts_id"]
            for i in range(len(row)):
                if row[i][1] not in partscodes:
                    continue
                info = {}
                for j in range(len(key)):
                    info[key[j]] = row[i][j]
                PartsInfo.append(info)
    except Exception as e:
        pass
    return render(request, 'QLGL/XJYW/JCJC_SEE_ADD.html',
                  {"check_id": check_id, "bridge_id": bridge_id, "PartsInfo": PartsInfo})


# 功能：经常检查病害位置选择之后保存
# 传入参数：request
# 返回参数：response
def QLXJ_XJYW_JCJC_DISEASE_POSITIONSAVE(request):
    check_record_id = request.POST.get('check_record_id', '')
    disease_id = request.POST.get('disease_id', '')
    bridge_member_id = request.POST.get('member_id', '')
    attrList = request.POST.get("attrList", "")
    attr = eval(attrList)
    try:
        for i in attr:
            row = MySQLDB.CommitMySql(
                "INSERT INTO `t_check_often_disease_attr`(`check_record_id`,`check_id`,`disease_id`,`attribute_id`,`attribute_code`,`attribute_name`,`attribute_value`,`param_type`,`member_no`,`parts_code`,`status`) select c.check_record_id,c.check_id,%s,a.id,a.code,a.name,'%s',a.param_type,b.member_name,b.parts_code,1 from t_sys_attribute a,t_bridge_member b,t_check_record c where a.id = %s and b.bridge_member_id = %s and c.check_record_id = %s;" % (
                    disease_id, i["value"], i["attr_id"], bridge_member_id, check_record_id))
        if (row != "ok"):
            raise Exception("病害位置保存失败")
        data = {
            "status": 1,
            "message": u"新增成功",
            "data": []
        }
    except Exception as e:
        data = {
            "status": 0,
            "message": u"新增失败:" + e.message,
            "data": []
        }
    return JsonResponse(data)


# 功能：定期检查病害记录保存
# 传入参数：request
# 返回参数：response
@authjson
def QLXJ_XJYW_JCJC_DISEASE_ADDSAVE(request):
    userid = request.COOKIES.get("userid")
    # 接收参数
    checkId = request.POST.get('check_id', -1)
    diseaseId = request.POST.get('disease_id', -1)
    memberId = request.POST.get('member_id', -1)
    scaleId = request.POST.get('scale_id', -1)
    position = request.POST.get('position', '')
    description = request.POST.get('description', '')
    remark = request.POST.get('remark', '')
    attrList = request.POST.get("attrList", "")
    if len(attrList) > 0:
        attr = eval(attrList)
    photoList = request.POST.get("photoList", "")
    if len(photoList) > 0:
        photo = eval(photoList)
    try:
        recordCode = Common.GenDocNum("t_check_record", "1")  # 定检生成编号
        if len(recordCode) == 0:
            raise Exception(u"编号生成失败")
        # 保存CheckRecord
        insertsql = "INSERT INTO `t_check_often_record`(`record_code`,`check_id`,`bridge_id`,`bridge_name`,`disease_id`,`disease_name`,`parts_code`,`member_id`,`member_name`,`member_no`,`check_date`,`level`,`max_level`,`disease_scale_id`,`status`,`position`,`description`,`remark`) select '%s',a.check_id,a.bridge_id,a.bridge_name,b.disease_id,b.disease_name,c.parts_code,c.bridge_member_id,c.notes,c.member_name,now(),d.level,(select max(level) from t_sys_disease_scale where disease_id = d.disease_id),d.disease_scale_id,1,'%s','%s','%s' from t_check_often a,t_sys_disease b,t_bridge_member c,t_sys_disease_scale d where a.check_id = '%s' and b.disease_id = '%s' and c.bridge_member_id = '%s' and d.disease_scale_id = '%s';" % (
            recordCode, position, description, remark, checkId, diseaseId, memberId, scaleId)
        row = MySQLDB.CommitMySql(insertsql)
        if row != "ok":
            raise Exception(u"数据保存失败1")
        record = MySQLDB.SelectMySql(
            "select check_record_id from t_check_often_record where record_code = '%s';" % recordCode)
        if len(record) == 0:
            raise Exception(u"数据保存失败2")
        recordid = record[0][0]
        # 保存属性记录
        for i in attr:
            # a = "INSERT INTO `t_check_often_disease_attr`(`check_record_id`,`check_id`,`disease_id`,`attribute_id`,`attribute_code`,`attribute_name`,`attribute_value`,`param_type`,`member_no`,`parts_code`,`status`) select c.check_record_id,c.check_id,%s,a.id,a.code,a.name,'%s',a.param_type,b.member_name,b.parts_code,1 from t_sys_attribute a,t_bridge_member b,t_check_record c where a.id = %s and b.bridge_member_id = %s and c.check_record_id = %s;" % (
            #         diseaseId, i["attr_value"], i["attr_id"], memberId, recordid)

            # print a
            row = MySQLDB.CommitMySql(
                "INSERT INTO `t_check_often_disease_attr`(`check_record_id`,`check_id`,`disease_id`,`attribute_id`,`attribute_code`,`attribute_name`,`attribute_value`,`param_type`,`member_no`,`parts_code`,`status`) select c.check_record_id,c.check_id,%s,a.id,a.code,a.name,'%s',a.param_type,b.member_name,b.parts_code,1 from t_sys_attribute a,t_bridge_member b,t_check_record c where a.id = %s and b.bridge_member_id = %s and c.check_record_id = %s;" % (
                    diseaseId, i["attr_value"], i["attr_id"], memberId, recordid))
            if row != "ok":
                raise Exception(u"属性数据保存失败3")
        if len(photoList) > 0:
            for i in photo:
                insertfiles = "INSERT INTO `t_check_often_file`(`check_record_id`,`name`,`url`,`member_name`,`disease_name`,`status`,`type`) select '%s','%s','%s',a.member_name,b.disease_name,1,1 from t_bridge_member a,t_sys_disease b where a.bridge_member_id = %s and b.disease_id = %s;" % (
                    recordid, i["file_name"], i["file_url"], memberId, diseaseId)
                row = MySQLDB.CommitMySql(insertfiles)
                if row != "ok":
                    raise Exception(u"保存图片数据保存失败")
        data = {
            "status": 1,
            "message": u"新增成功",
            "data": []
        }
    except Exception as e:
        data = {
            "status": 0,
            "message": u"新增失败:" + e.message,
            "data": []
        }
    return JsonResponse(data)


# 功能：定期检查病害记录修改
# 传入参数：request
# 返回参数：response
@auth
def QLXJ_XJYW_JCJC_DISEASE_MODIFY(request):
    checkRecordId = request.GET.get("check_record_id", -1)
    checkRecordInfo = []
    diseaseInfo = []
    levelInfo = []
    attrInfo = []
    photoInfo = []

    try:
        row = MySQLDB.SelectMySql(
            "select disease_id,disease_name,a.parts_code,parts_name,member_id,member_name,member_no,level,disease_scale_id,position,description,remark from t_check_often_record a inner join t_sys_parts b on a.parts_code = b.parts_code where check_record_id = '%s' and a.status = 1;" % (
                checkRecordId))
        if len(row) > 0:
            key = ['disease_id', 'disease_name', 'parts_code', 'parts_name', 'member_id', 'member_name', 'member_no',
                   'level', 'disease_scale_id', 'position', 'description', 'remark']
            for i in range(len(row)):
                info = {}
                for j in range(len(key)):
                    info[key[j]] = row[i][j]
                checkRecordInfo.append(info)
            memberId = checkRecordInfo[0]["member_id"]
            diseaseId = checkRecordInfo[0]["disease_id"]
        else:
            raise Exception(u"病害信息错误")
        row = Common.GetDiseaseByMemberId(memberId)
        if len(row) > 0:
            for m in range(len(row)):
                info = {}
                info["disease_id"] = row[m][0]
                info["disease_name"] = row[m][1]
                diseaseInfo.append(info)
        row = Common.GetDiseaseLevel(diseaseId)
        if len(row) > 0:
            for m in range(len(row)):
                info = {}
                info["disease_scale_id"] = row[m][0]
                info["level"] = row[m][1]
                info["sumup"] = row[m][2]
                levelInfo.append(info)
        sqlCom = "select attribute_id,attribute_name,param_type,attribute_value from t_check_often_disease_attr where check_record_id = '%s' and status = 1;" % checkRecordId
        row = MySQLDB.SelectMySql(sqlCom)
        if len(row) > 0:
            for m in range(len(row)):
                info = {}
                info["attr_id"] = row[m][0]
                info["attr_name"] = row[m][1]
                info["type"] = row[m][2]
                info["attr_value"] = row[m][3]
                attrInfo.append(info)
        sqlCom = "select check_file_id,name,url from t_check_often_file where check_record_id = '%s' and status = 1;" % checkRecordId
        print sqlCom
        row1 = MySQLDB.SelectMySql(sqlCom)
        if len(row1) > 0:
            for m in range(len(row1)):
                info = {}
                info["file_id"] = row1[m][0]
                info["file_name"] = row1[m][1]
                info["file_url"] = row1[m][2]
                photoInfo.append(info)

    except Exception as e:
        return e
    return render(request, 'QLGL/XJYW/JCJC_SEE_MODIFY.html',
                  {"check_record_id": json.dumps(checkRecordId), "checkRecordInfo": checkRecordInfo,
                   "diseaseInfo": diseaseInfo, "levelInfo": levelInfo, "attrInfo": json.dumps(attrInfo),
                   "photoInfo": photoInfo})


# 功能：定期检查病害记录修改保存
# 传入参数：request
# 返回参数：response
@authjson
def QLXJ_XJYW_JCJC_DISEASE_MODIFYSAVE(request):
    # 接收参数
    checkRecordId = request.POST.get('check_record_id', -1)
    diseaseId = request.POST.get('disease_id', -1)
    memberId = request.POST.get('member_id', -1)
    scaleId = request.POST.get('scale_id', -1)
    position = request.POST.get('position', '')
    description = request.POST.get('description', '')
    remark = request.POST.get('remark', '')
    attrList = request.POST.get("attrList", "")
    if len(attrList) > 0:
        attr = eval(attrList)
    photoList = request.POST.get("photoList", "")
    if len(photoList) > 0:
        photo = eval(photoList)
    originalAttrIds = []
    originalFileIds = []
    try:
        # 保存CheckRecord
        updateCmd = "UPDATE `t_check_often_record` SET `disease_id` = '%s',`disease_name` = (select disease_name from t_sys_disease where disease_id = '%s'),`level` = (select level from t_sys_disease_scale where disease_scale_id = '%s'),`max_level` = (select max(level) from t_sys_disease_scale where disease_id = '%s'),`disease_scale_id` = '%s',`position` = '%s',`description` = '%s',`remark` = '%s',`update_date` = now() WHERE `check_record_id` = '%s';" % (
            diseaseId, diseaseId, scaleId, diseaseId, scaleId, position, description, remark, checkRecordId)
        row = MySQLDB.CommitMySql(updateCmd)
        if (row != "ok"):
            raise Exception(u"定期检查数据保存失败")
        # 保存属性记录,先判断是否更新，若更新，修改数据
        if len(attrList) > 0:
            # 判断是否更新，新增的insert，改变的del
            # 提取原有属性数据
            selCmd = "select attribute_id from t_check_often_disease_attr where check_record_id = '%s' and status = 1;" % checkRecordId
            row = MySQLDB.SelectMySql(selCmd)
            if len(row) > 0:
                originalAttrIds = [str(w[0]) for w in row]
            inAttrIds = [w["attr_id"] for w in attr]
            # 比较差集，新列表有的，原来没得的，定义为新增加
            insertIds = list(set(inAttrIds).difference(set(originalAttrIds)))
            if len(insertIds):
                for i in [w for w in attr if w["attr_id"] in insertIds]:
                    insertCmd = "INSERT INTO `t_check_often_disease_attr`(`check_record_id`,`check_id`,`disease_id`,`attribute_id`,`attribute_code`,`attribute_name`,`attribute_value`,`param_type`,`member_no`,`parts_code`,`status`) select c.check_record_id,c.check_id,%s,a.id,a.code,a.name,'%s',a.param_type,b.member_name,b.parts_code,1 from t_sys_attribute a,t_bridge_member b,t_check_record c where a.id = %s and b.bridge_member_id = %s and c.check_record_id = %s;" % (
                        diseaseId, i["attr_value"], i["attr_id"], memberId, checkRecordId)
                    row = MySQLDB.CommitMySql(insertCmd)
                    if row != "ok":
                        raise Exception("修改病害记录属性失败")
            # 比较差集，缺少的东西删除
            deleteIds = list(set(originalAttrIds).difference(set(inAttrIds)))
            if len(deleteIds):
                for i in deleteIds:
                    deleteCmd = "update t_check_often_disease_attr set status = 0,update_date=now() where check_record_id = '%s' and attribute_id = '%s';" % (
                        checkRecordId, i)
                    row = MySQLDB.CommitMySql(deleteCmd)
                    if row != "ok":
                        raise Exception("修改病害记录属性失败")
            for i in [w for w in attr if w["attr_id"] not in insertIds]:
                updateCmd = "update t_check_often_disease_attr set attribute_value = '%s',update_date=now() where check_record_id = '%s' and attribute_id = '%s';" % (
                    i["attr_value"], checkRecordId, i["attr_id"])
                row = MySQLDB.CommitMySql(updateCmd)
                if row != "ok":
                    raise Exception("修改病害记录属性失败")
        # 保存图片信息，存在2种情况：
        # 1、已有数据删除，需要把所有数据提取出来之后，不存在的数据移除；
        # 2、新增数据，插入数据库
        if len(photoList) > 0:
            # 提取原有数据
            selCmd = "select check_file_id from t_check_often_file where check_record_id = '%s' and status = 1;" % checkRecordId
            row = MySQLDB.SelectMySql(selCmd)

            if len(row) > 0:
                originalFileIds = [str(w[0]) for w in row]
            inFileIds = [w["file_id"] for w in photo]
            # 比较数据，原来有的，新的没有，判断被删除数据
            deleteIds = list(set(originalFileIds).difference(set(inFileIds)))
            if len(deleteIds) > 0:
                for i in deleteIds:
                    deleteCmd = "update t_check_often_file set status = 0,update_date=now() where check_file_id = '%s';" % i
                    row = MySQLDB.CommitMySql(deleteCmd)
                    if row != "ok":
                        raise Exception("修改病害记录图片失败")
            for i in [w for w in photo if w["file_id"] == "0"]:
                insertCmd = "INSERT INTO `t_check_often_file`(`check_record_id`,`name`,`url`,`member_name`,`disease_name`,`status`,`type`) select '%s','%s','%s',a.member_name,b.disease_name,1,1 from t_bridge_member a,t_sys_disease b where a.bridge_member_id = %s and b.disease_id = %s;" % (
                    checkRecordId, i["file_name"], i["file_url"], memberId, diseaseId)
                row = MySQLDB.CommitMySql(insertCmd)
                if row != "ok":
                    raise Exception("修改病害记录图片失败")
        data = {
            "status": 1,
            "message": u"新增成功",
            "data": []
        }
    except Exception as e:
        data = {
            "status": 0,
            "message": u"新增失败:" + e.message,
            "data": []
        }
    return JsonResponse(data)


# 功能：定期检查病害记录删除
# 传入参数：request
# 返回参数：response
@authjson
def QLXJ_XJYW_JCJC_DISEASE_DELETESAVE(request):
    checkRecordId = request.GET.get("check_record_id", -1)
    try:
        if checkRecordId > 0:
            delCmd = "update t_check_often_record set status = 0,update_date = now() where check_record_id = '%s';" % checkRecordId
            row = MySQLDB.CommitMySql(delCmd)
            if row != "ok":
                raise Exception(u"病害记录删除失败")
            data = {
                "status": 1,
                "message": u"病害记录删除成功",
                "data": []
            }
    except Exception as e:
        data = {
            "status": 0,
            "message": e.message,
            "data": []
        }
    return JsonResponse(data)


# 功能：查看定期检查病害记录媒体信息
# 传入参数：request
# 返回参数：response
@authjson
def QLXJ_XJYW_JCJC_DISEASE_MEDIA(request):
    checkRecordId = request.GET.get("check_record_id", -1)
    photoList = []
    try:
        if checkRecordId > 0:
            selCmd = "select check_file_id,name,url from t_check_often_file where check_record_id = '%s' and status = 1;" % checkRecordId
            row = MySQLDB.SelectMySql(selCmd)
            if len(row) > 0:
                for i in range(len(row)):
                    info = {}
                    item = row[i]
                    info["file_id"] = item[0]
                    info["file_name"] = item[1]
                    info["file_url"] = item[2]
                    photoList.append(info)
            data = {
                "status": 1,
                "message": u"查询成功",
                "data": photoList
            }
    except Exception as e:
        data = {
            "status": 0,
            "message": e.message,
            "data": []
        }
    return JsonResponse(data)


# 经常检查病害位置弹窗 页面
@auth
def QLXJ_XJYW_JCJC_DISEASE_POSITION1(request):
    member_id = request.GET.get('member_id', 0)
    disease_id = request.GET['disease_id']
    # record_id = request.GET['check_record_id']

    PositionInfo = []
    AttrInfo = []
    one = []
    two = []
    three = []
    four = []
    try:
        row = MySQLDB.SelectMySql(
            "SELECT b.id,b.name,b.remark from t_disease_attribute a inner join t_sys_attribute b on a.attribute_id = b.id and b.status = 1 where a.disease_id = '%s' and a.param_type = 5 order by orderby;" % disease_id)
        if len(row) > 0:
            key = ["id", "name", "remark"]
            for i in range(len(row)):
                info = {}
                for j in range(len(key)):
                    info[key[j]] = row[i][j]
                AttrInfo.append(info)
        row1 = Common.GetPositionByDisease(member_id, disease_id)
        if len(row1) > 0:
            for m in range(len(row1)):
                info = {}
                info["attr_id"] = row1[m][1]
                info["attr_name"] = row1[m][2]
                if (1 == row1[m][0]):
                    one.append(info)
                if (2 == row1[m][0]):
                    two.append(info)
                if (3 == row1[m][0]):
                    three.append(info)
                if (4 == row1[m][0]):
                    four.append(info)
                    # PositionInfo.append(info)
    except Exception as e:
        pass
    if len(one):
        info = {}
        info["type"] = "1"
        info["itme"] = one
        PositionInfo.append(info)
    if len(two):
        info = {}
        info["type"] = "2"
        info["itme"] = two
        PositionInfo.append(info)
    if len(three):
        info = {}
        info["type"] = "3"
        info["itme"] = three
        PositionInfo.append(info)
    if len(four):
        info = {}
        info["type"] = "4"
        info["itme"] = four
        PositionInfo.append(info)
    # return JsonResponse({"data":PositionInfo})
    return render(request, 'QLGL/XJYW/JCJC_SEE_MODIFY_POSITION.html',
                  {"PositionInfo": PositionInfo, "AttrInfo": AttrInfo, "disease_id": disease_id,
                   "member_id": member_id})


# 经常检查病害位置弹窗 页面
@auth
def QLXJ_XJYW_JCJC_DISEASE_POSITION(request):
    member_id = request.GET.get('member_id', 0)
    disease_id = request.GET['disease_id']
    # record_id = request.GET['check_record_id']

    PositionInfo = []
    AttrInfo = []
    one = []
    two = []
    three = []
    four = []
    try:
        row = MySQLDB.SelectMySql(
            "SELECT b.id,b.name,b.remark from t_disease_attribute a inner join t_sys_attribute b on a.attribute_id = b.id and b.status = 1 where a.disease_id = '%s' and a.param_type = 5 order by orderby;" % disease_id)
        if len(row) > 0:
            key = ["id", "name", "remark"]
            for i in range(len(row)):
                info = {}
                for j in range(len(key)):
                    info[key[j]] = row[i][j]
                AttrInfo.append(info)
        row1 = Common.GetPositionByDisease(member_id, disease_id)
        if len(row1) > 0:
            for m in range(len(row1)):
                info = {}
                info["attr_id"] = row1[m][1]
                info["attr_name"] = row1[m][2]
                if (1 == row1[m][0]):
                    one.append(info)
                if (2 == row1[m][0]):
                    two.append(info)
                if (3 == row1[m][0]):
                    three.append(info)
                if (4 == row1[m][0]):
                    four.append(info)
                    # PositionInfo.append(info)
    except Exception as e:
        pass
    if len(one):
        info = {}
        info["type"] = "1"
        info["itme"] = one
        PositionInfo.append(info)
    if len(two):
        info = {}
        info["type"] = "2"
        info["itme"] = two
        PositionInfo.append(info)
    if len(three):
        info = {}
        info["type"] = "3"
        info["itme"] = three
        PositionInfo.append(info)
    if len(four):
        info = {}
        info["type"] = "4"
        info["itme"] = four
        PositionInfo.append(info)
    # return JsonResponse({"data":PositionInfo})
    return render(request, 'QLGL/XJYW/JCJC_SEE_ADD_POSITION.html',
                  {"PositionInfo": PositionInfo, "AttrInfo": AttrInfo, "disease_id": disease_id,
                   "member_id": member_id})


# 功能：定期检查新增病害选择部件之后再选择构件
# 传入参数：request
# 返回参数：response
@authjson
def QLXJ_XJYW_JCJC_SEE_DATA_MEMBER(request):
    check_id = request.GET['check_id']
    bridge_id = request.GET['bridge_id']
    parts_code = request.GET['parts_code']
    MemberInfo = []
    try:
        row = MySQLDB.SelectMySql(
            "SELECT bridge_member_id,member_name,notes from t_bridge_member a where bridge_id = '%s' and parts_code = '%s' and exists(select 1 from t_check_often_items b where status = 1 and check_id = '%s' and b.parts_sub_id = a.parts_sub_id);" % (
                bridge_id, parts_code, check_id))
        # 根据检查项，过滤对应的构件信息，不在检查范围的数据，不予显示
        if len(row) > 0:
            for m in range(len(row)):
                info = {}
                info["bridge_member_id"] = row[m][0]
                info["member_no"] = row[m][1]
                info["member_name"] = row[m][2]
                MemberInfo.append(info)
        data = {
            "status": 1,
            "message": u"查看页面数据成功",
            "data": MemberInfo
        }
    except Exception as e:
        data = {
            "status": 0,
            "message": u"查看页面数据失败",
            "data": []
        }
    return JsonResponse(data)


def QLXJ_XJYW_JCJC_DISEASE_MOVE(request):
    checkRecordId = request.GET.get("check_record_id", -1)
    checkRecordInfo = {}
    bridgeId = -1
    bridgeInfo = []
    partsInfo = []
    memberInfo = []
    try:
        selCmd = "select bridge_id,bridge_name,parts_code,member_id,member_name,member_no,check_id from t_check_often_record where check_record_id = '%s';" % checkRecordId
        row = MySQLDB.SelectMySql(selCmd)
        keys = ["bridge_id", "bridge_name", "parts_code", "member_id", "member_name", "member_no", "check_id"]
        if len(row) > 0:
            i = 0
            for j in range(len(keys)):
                checkRecordInfo[keys[j]] = row[i][j]
        else:
            raise Exception(u"定期检查数据异常")
        # 桥梁信息
        selCmd = "select bridge_id,bridge_name from t_bridge_base where status = 1;"
        row = MySQLDB.SelectMySql(selCmd)
        if len(row) > 0:
            for i in range(len(row)):
                info = {}
                info["bridge_id"] = row[i][0]
                info["bridge_name"] = row[i][1]
                bridgeInfo.append(info)
        # 部件信息
        row = Common.GetPartsListByBridge(checkRecordInfo["bridge_id"])
        # 数据过滤，设置检查部件后，选择的部件才可以选择
        parts = Common.ConverToDICT(Common.GetJCJCPartSub(checkRecordInfo["check_id"]),
                                    ["check_item_id", "check_id", "parts_code", "parts_sub_id", "parts_sub_name",
                                     "status", "bridge_parts_id"])
        partscodes = [w["parts_code"] for w in parts]
        if len(row) > 0:
            for i in range(len(row)):
                if row[i][1] not in partscodes:
                    continue
                info = {}
                info["parts_code"] = str(row[i][1])
                info["parts_name"] = row[i][2]
                partsInfo.append(info)
        # 构件信息
        selCmd = "SELECT bridge_member_id,member_name,notes from t_bridge_member where bridge_id = '%s' and parts_code = '%s' and status = 1;" % (
            checkRecordInfo["bridge_id"], checkRecordInfo["parts_code"])
        row = MySQLDB.SelectMySql(selCmd)
        if len(row) > 0:
            for m in range(len(row)):
                info = {}
                info["bridge_member_id"] = row[m][0]
                info["member_name"] = row[m][2]
                info["member_no"] = row[m][1]
                memberInfo.append(info)

    except Exception as e:
        pass
    return render(request, "QLGL/XJYW/JCJC_SEE_MOVE.html",
                  {"checkRecordId": checkRecordId, "checkRecordInfo": checkRecordInfo, "bridgeInfo": bridgeInfo,
                   "partsInfo": partsInfo, "memberInfo": memberInfo})


def QLXJ_XJYW_JCJC_DISEASE_MOVESAVE(request):
    checkRecordId = request.GET.get("check_record_id", -1)
    bridgeId = request.GET.get("bridge_id", -1)
    memberId = request.GET.get("member_id", -1)
    checkId = 0
    checkRecordInfo = {}
    try:
        if checkRecordId > 0:
            selCmd = "select bridge_id,member_id from t_check_often_record where check_record_id = '%s';" % checkRecordId
            row = MySQLDB.SelectMySql(selCmd)
            keys = ["bridge_id", "member_id"]
            if len(row) > 0:
                i = 0
                for j in range(len(keys)):
                    checkRecordInfo[keys[j]] = str(row[i][j])
            else:
                raise Exception(u"定期检查数据异常")
            # 检查选择桥梁是否有检测数据，若没有，则提示用户新增检测
            selCmd = "select check_id from t_check_often where bridge_id = '%s';" % bridgeId
            row = MySQLDB.SelectMySql(selCmd)
            if len(row) > 0:  # 存在检测记录
                checkId = row[0][0]
            else:
                raise Exception("所选桥梁没有定期检查数据，请先建立桥梁定期检查数据.")
            # 比较数据
            # 比较桥梁信息是否修改
            # update t_check_record a,t_bridge_base b,t_bridge_member c set a.bridge_id = b.bridge_id,a.bridge_name =b.bridge_name,a.parts_code = c.parts_code,a.member_id = c.bridge_member_id,a.member_name=c.notes,a.member_no=c.member_name where a.check_record_id = 5 and b.bridge_id = 4 and c.bridge_member_id = 82;
            updateCmdHand = "update t_check_often_record a "
            updateCmdSet = "set a.update_date = now() "
            updateCmdWhere = " where a.check_record_id='%s' " % checkRecordId
            updateFlag = 0
            if bridgeId != checkRecordInfo["bridge_id"]:
                # 更新桥梁信息
                updateFlag = 1
                updateCmdHand += ",t_bridge_base b "
                updateCmdSet += ",a.bridge_id = b.bridge_id,a.bridge_name =b.bridge_name,a.check_id = '%s' " % checkId
                updateCmdWhere += " and b.bridge_id = '%s' " % bridgeId
            if memberId != checkRecordInfo["member_id"]:
                # 更新构件信息
                updateFlag = 1
                updateCmdHand += ",t_bridge_member c "
                updateCmdSet += ",a.parts_code = c.parts_code,a.member_id = c.bridge_member_id,a.member_name=c.notes,a.member_no=c.member_name "
                updateCmdWhere += " and c.bridge_member_id = '%s' " % memberId
            if updateFlag > 0:
                # 执行更新
                updateCmd = updateCmdHand + updateCmdSet + updateCmdWhere
                row = MySQLDB.CommitMySql(updateCmd)
                if row != "ok":
                    raise Exception("数据更新失败")

        else:
            raise Exception(u"记录编号不存在")
        data = {
            "status": 1,
            "message": u"修改成功",
            "data": []
        }
    except Exception as e:
        data = {
            "status": 0,
            "message": e.message,
            "data": []
        }
    return JsonResponse(data)

